select * from tab1;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
select * from empt;
+------+------+------+
| id | l1 | l2 |
+------+------+------+
| 10 | 1 | 100 |
| 11 | 1 | 101 |
| 12 | 1 | 102 |
| 13 | 2 | 100 |
| 14 | 4 | 101 |
+------+------+------+
empt表中的L1列是tab1.id的外键。
我需要在tab1
专栏中没有100
的l2
的ID
我试过的查询但没有得到正确的结果。
select tab1.id from tab1 left join empt on tab1.id = empt.l1
where l2 not in(100);
输出我想要的是
+------+
|tab1.id|
+------+
| 3 |
| 4 |
+------+
SELECT DISTINCT x.*
FROM tab1 x
LEFT
JOIN empt y
ON y.l1 = x.id
AND y.l2 IN(100)
WHERE y.l1 IS NULL;
SELECT id
FROM tab1
WHERE id NOT IN (SELECT l1 FROM empt WHERE l2 = 100);
你不需要使用左连接一个简单的选择Sql语句可以解决你的问题:
select id from tab1 where id not in(select l1 from empt where l2 = 100)
最好的祝福
使用NOT EXISTS
select t1.id
from tab1 t1
where not exists(select 1 from empt t2 where t2.l1 = t1.id and t2.l2 = 100)
SELECT Distinct tab1.id
FROM tab1
LEFT JOIN
(SELECT * FROM empt WHERE empt.12 = 100) t on tab1.id = t.l1
WHERE t.l1 IS NULL
在您的查询中添加一个组
select tab1.id
from tab1
left join empt on tab1.id = empt.l1
where l2 not in (100)
group by tab1.id