gpt4 book ai didi

mysql - 选择两个表中不存在的值

转载 作者:行者123 更新时间:2023-11-29 01:26:37 24 4
gpt4 key购买 nike

table1            table2             table3          Expected Result-------------     --------------     -------------   ------| id | col1 |     | id | col1  |     | id | col1 |   | id |-------------     --------------     -------------   ------| 1  | val1 |     | 2  | val1  |     | 3  | val1 |   | 1  || 2  | val2 |     | 2  | val2  |     | 3  | val2 |   | 6  || 3  | val3 |     | 4  | val1  |     | 5  | val1 |   ------| 4  | val4 |     | 4  | val2  |     | 5  | val2 || 5  | val5 |     --------------     ------------| 6  | val6 |-------------

我想选择不在table2和table3中的table1的id。为此,我编写了一个查询,但执行起来需要花费太多时间。请建议我更好的查询。

我使用的查询是SELECT DISTINCT(id) FROM table1 WHERE yacht_id NOT IN(SELECT id FROM table2 UNION SELECT id FROM table3 ORDER BY id)

最佳答案

您的查询没问题,但另一种方法是使用 left joins

select  t1.id
from table1 t1
left join
table2 t2
on t1.id = t2.id
left join
table3 t3
on t1.id = t3.id
where t2.id is null and t3.id is null

这将保留 table1 中的所有行,当 id 在 table2table3 上不可用时,将它们与 null 匹配

从那里您所要做的就是在 table2table3 上过滤具有 null 的行。

关于mysql - 选择两个表中不存在的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43344132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com