我有以下表格:
Table A
id | name
1 | foo
2 | bar
Table B
id | name | default
1 | 123 | 1
2 | 321 | 0
3 | 456 | 1
Table C
A_id | B_id
1 | 2
1 | 3
现在我想获得不在C中的A-B对(条件是这些对具有B.default = 1)
所以预期的结果是:
A_id | B_id
1 | 1
2 | 1
2 | 3
但我对如何加入表B感到困惑:
SELECT A.id, B.id
FROM A
LEFT OUTER JOIN C
ON C.A_id = A.id
LEFT OUTER JOIN B
AND C.B_id = B.id
AND B.default = 1
答案 0 :(得分:1)
首先生成所有A对,然后与C
进行比较NOT EXISTS比LEFT JOIN稍微更正确(反半连接)
SELECT
X.A_id, X.B_id
FROM
(
SELECT
A.id AS A_id,
B.id AS B_id
FROM
A CROSS JOIN B
WHERE
B.default = 1
) X
WHERE
NOT EXISTS (SELECT *
FROM
C
WHERE
C.A_id = X.A_id
AND
C.B_id = X.B_id)
然而,这给出了这个结果。只有(1,3)的C元组匹配4个A-B对
A_id | B_id
1 | 1
2 | 1
2 | 3