繁体   English   中英

Mysql:Select 行来自不在第三个表中的 2 个表

[英]Mysql: Select rows from 2 tables that are not in a third table

我有三个表员工,客户和帐户。 我想 select 在员工和客户中找到但不在帐户中的所有行。 我试过 SELECT *FROM 员工,没有 id 的客户(从帐户中选择 id)并且它没有用,但如果我删除员工或客户它可以工作

如果员工或客户都没有帐户,您可以合并 2 个表,然后测试

with cte as
(
Select 'e' src,id, name from employees
union all
Select 'c' src,id, name from customers
)
select * 
from cte 
where not exists (select 1 from accounts where accounts_id = cte.id);

或者您可以使用交叉连接(或不带 where 子句的逗号连接)

SELECT  
FROM employees e, customers c 
where not exists (select 1 from accounts where accounts_id = e.id) and
      not exists (select 1 from accounts where accounts_id = c.id);

关键是您必须从两个表中测试 id。 联合有一个 id 要测试,交叉连接有两个。 使用不存在意味着查询比 in(s) 更有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM