Mysql 查询不在另一个 table
Mysql Query Not in another table
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 table 中的 L1 列是 tab1.id 的外键。
我需要 tab1
的 ID,它在 l2
列
中没有 100
我试过但没有得到正确结果的查询。
select tab1.id from tab1 left join empt on tab1.id = empt.l1
where l2 not in(100);
我想要的输出是
+------+
|tab1.id|
+------+
| 3 |
| 4 |
+------+
SELECT id
FROM tab1
WHERE id NOT IN (SELECT l1 FROM empt WHERE l2 = 100);
为您的查询添加分组依据
select tab1.id
from tab1
left join empt on tab1.id = empt.l1
where l2 not in (100)
group by tab1.id
使用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 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 Sql 语句就可以解决您的问题:
select id from tab1 where id not in(select l1 from empt where l2 = 100)
此致
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 table 中的 L1 列是 tab1.id 的外键。
我需要 tab1
的 ID,它在 l2
列
100
我试过但没有得到正确结果的查询。
select tab1.id from tab1 left join empt on tab1.id = empt.l1
where l2 not in(100);
我想要的输出是
+------+
|tab1.id|
+------+
| 3 |
| 4 |
+------+
SELECT id
FROM tab1
WHERE id NOT IN (SELECT l1 FROM empt WHERE l2 = 100);
为您的查询添加分组依据
select tab1.id
from tab1
left join empt on tab1.id = empt.l1
where l2 not in (100)
group by tab1.id
使用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 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 Sql 语句就可以解决您的问题:
select id from tab1 where id not in(select l1 from empt where l2 = 100)
此致