我有以下表格:
TABLE_A
| some_id | entity_id| tableB_id| position |
|-------------------|----------|----------|----------|
| 388 | 8 | 5783 | 0 |
| 389 | 8 | 776 | 1 |
| 390 | 8 | 5765 | 2 |
| 391 | 8 | 5743 | 3 |
| 392 | 8 | 6167 | 4 |
| 393 | 8 | 6168 | 5 |
| 394 | 8 | 6169 | 6 |
| 708 | 11 | 501 | 3 |
TABLE_B
| some_id | key_1 | key2 | tableC_id |isSomeCheck|isOtherCheck|
|-------------------|---------|-------------- |-----------|-----------|------------|
| 776 | null | pqrstuvw1234| 311 | 1 | 0 |
| 5743 | sfrwt0 | sofdsfsdr456| 1829 | 1 | 0 |
| 5765 | null | abcdefgh4567| 321 | 1 | 0 |
| 5783 | null | something341| 1841 | 1 | 0 |
| 6167 | somer9 | null | 1956 | 0 | 0 |
| 6168 | richt6 | null | 1957 | 0 | 0 |
| 6169 | done60 | null | 1957 | 0 | 0 |
TABLE_C
| some_id | key_1 | sortName |
|-------------------|----------|----------|
| 311 | tes456 | WWW |
| 321 | don890 | UNK |
| 1829 | som123 | ILA |
| 1841 | ken980 | ARI |
| 1956 | lam123 | KOR |
| 1957 | kes648 | ERO |
isSomeCheck
或 isOtherCheck
必须为 1.
我正在运行的当前查询返回结果,其中只有 TABLE_B 中的 key_1 存在:
SELECT TABLE_A.some_id FROM TABLE_B
JOIN TABLE_A
ON TABLE_A.tableB_id = TABLE_B.some_id
JOIN (SELECT tableB.some_id AS tableBID,
tableC.sortName AS tableCSortName
FROM TABLE_B AS tableB
INNER JOIN TABLE_C AS tableC
ON tableB.tableC_id = tableC.some_id
GROUP BY tableB.some_id)
ON TABLE_A.tableB_id = tableBID WHERE TABLE_B.key_1 in (select distinct(key_1) from TABLE_B where key_1 = TABLE_B.key_1 and TABLE_B.isRequired = 1 or TABLE_B.isChecked = 1) AND entity_id = 8 ORDER BY TABLE_A.position
输出:
| some_id |
|-------------------|
| 391 |
一切正常,除了如果 TABLE_B 中缺少 key_1 并且 key_2 像 OR 条件一样存在,我还想从 TABLE_A 中获取
some_id
。基本上,我也想在输出中考虑 key_2。
所以,我的预期输出是这样的:
| some_id |
|-------------------|
| 388 |
| 389 |
| 390 |
| 391 |
我试过并返回correct输出:
SELECT TABLE_A.some_id FROM TABLE_B
JOIN TABLE_A
ON TABLE_A.tableB_id = TABLE_B.some_id
JOIN (SELECT tableB.some_id AS tableBID,
tableC.sortName AS tableCSortName
FROM TABLE_B AS tableB
INNER JOIN TABLE_C AS tableC
ON tableB.tableC_id = tableC.some_id
GROUP BY tableB.some_id)
ON TABLE_A.tableB_id = tableBID
WHERE
(TABLE_B.key_2 in (select distinct(key_2) from TABLE_B where key_2 = TABLE_B.key_2 and TABLE_B.isSomeCheck = 1 or TABLE_B.isOtherCheck = 1) or
TABLE_B.key_1 in (select distinct(key_1) from TABLE_B where key_1 = TABLE_B.key_1 and TABLE_B.isSomeCheck = 1 or TABLE_B.isOtherCheck = 1))
AND entity_id = 8 ORDER BY TABLE_A.position;
这是实现我需要的输出的正确方法,还是有更好的方法来实现这个,以便我可以在上面的查询中更新
WHERE
子句?
我想删除在两个选择不同的查询中检查 isSomeCheck 和 isOtherCheck 的重复代码。谢谢!