Mysql Query不在另一个表中

问题描述 投票:1回答:6
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专栏中没有100l2的ID

我试过的查询但没有得到正确的结果。

select tab1.id from tab1 left join empt on tab1.id = empt.l1
where l2 not in(100);

输出我想要的是

+------+
|tab1.id|
+------+
|    3 |
|    4 |
+------+
mysql sql database psql
6个回答
1
投票
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;

2
投票

SELECT id FROM tab1 WHERE id NOT IN (SELECT l1 FROM empt WHERE l2 = 100);


2
投票

你不需要使用左连接一个简单的选择Sql语句可以解决你的问题:

select id from tab1 where id not in(select l1 from empt where l2 = 100)

最好的祝福


1
投票

使用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)

1
投票
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

-1
投票

在您的查询中添加一个组

select tab1.id 
from tab1 
    left join empt on tab1.id = empt.l1 
where l2 not in (100) 
group by tab1.id
© www.soinside.com 2019 - 2024. All rights reserved.