簡體   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