首页 > 解决方案 > 我有一个主表和一个来自 sql 查询的结果。如何加入这些主表和一个结果集以获取丢失的 ID

问题描述

表 1:“材料”

id
1
2
3
4
5

询问:

SELECT ID FROM 
(Select * From
 (Select Distinct(ID)  from tablex Union All 
Select Distinct(ID) from tabley Union All 
Select Distinct(ID) from tablez Union All )

来自上述查询的 o/p 是 1,2 &3

结局输出要求:4 5

标签: mysqlsql

解决方案


如果您想要主表中的 id 而不是子表中的 id,您可以使用not exists

select m.*
from master m
where not exists (select 1 from child1 c1 where c1.id = m.id) and
      not exists (select 1 from child2 c2 where c2.id = m.id);

推荐阅读