tableA
id a_id b_id
1 100 200
2 101 201
3 100 202
tableB
id a_id b_id
2 100 200
3 201 101
4 203 100
所以我希望得到a_id=100
的计数,但除了tableB
所以
in tableA i got 2:
1 100 200
3 100 202
但是{B}中存在100/200
,因此结果为1
如何编写sql?
答案 0 :(得分:2)
您可以使用NOT EXISTS
:
SELECT COUNT(1)
FROM TableA AS A
WHERE NOT EXISTS (
SELECT NULL
FROM TableB AS B
WHERE B.a_id = A.a_id
AND B.b_id = A.b_id
)
AND A.a_id = 100
如果您想使用left join
:
SELECT COUNT(1)
FROM TableA AS A
LEFT JOIN TableB AS B
ON B.a_id = A.a_id
AND B.b_id = A.b_id
WHERE B.a_id IS NULL
AND A.a_id = 100
答案 1 :(得分:0)
SELECT count(*)
FROM tableA a
WHERE a_id = 100 AND NOT EXISTS
(
SELECT *
FROM tableB b
WHERE b.a_id = a.a_id AND b.b_id = a.b_id
)