![](/img/trans.png)
[英]MySql multiple select from two tables and join their results to a third table
[英]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.