我试图弄清楚如何使用连接获得相同的结果,因为我会使用不存在的条件。
例如,如果我有以下两个表:
表1
--------------
|ID | EXT_ID |
|1 | A |
|2 | B |
|3 | C |
--------------
表2
-------------------------
|EXT_ID | TB1_ID |PRIMARY|
|A | 1 |1 |
|A | 1 |0 |
|B | 2 |0 |
|B | 2 |0 |
-------------------------
如果我希望从表1中找到表2中没有主要标志1的记录,对于实际在表2中有子项的记录(排除孤儿),我可以简单地写一下以下(预计只返回表1中的ID 2):
SELECT TB1.ID FROM Table1 TB1
JOIN Table2
ON Table1.EXT_ID = Table2.EXT_ID
WHERE Table2.Primary = 0
AND NOT EXISTS
(
SELECT * FROM Table2 TB2
WHERE TB1.ID = TB2.TB1_ID
AND TB2.PRIMARY = 1
)
有没有办法用连接做到这一点?如果是这样,使用not exists和join之间会有很大的效率吗?
提前致谢!
编辑:修复表格。
答案 0 :(得分:1)
with x as (select Ext_ID, Tb1_ID, Sum(Primary) as sum_primary
from Table2 group by Ext_ID,Tb1_ID)
SELECT TB1.ID
FROM Table1 TB1 JOIN x
ON Table1.EXT_ID = x.EXT_ID
where x.sum_primary = 0
您可以使用CTE。
答案 1 :(得分:0)
SELECT
TB1.ID, TB1.EXT_ID
FROM
TABLE1 TB1
JOIN TABLE2 TB2 ON TB1.ID = TB2.TB1_ID AND TB1.EXT_ID = Table2.EXT_ID
GROUP BY
TB1.ID, TB1.EXT_ID
HAVING MAX(TB2.[PRIMARY]) = 0