簡體   English   中英

SQL中的左連接以識別某些行

[英]Left join in SQL to identify certain rows

下表A:

客戶 ID 代碼
1 101
1 102
1 103
2 201

表 B:

客戶 ID 代碼
1 101
1 102

表 B 只有客戶 1,並且僅包含客戶 1 的兩個產品代碼。我想識別表 B 中不存在於表 B 中的客戶代碼。

客戶 ID 代碼
1 103

為此,我在 cust_id 和代碼上執行了表 A 左連接表 B,並認為表 B 中代碼為空值的那些會給出所需的結果,但它似乎不起作用。 如果有人能說出正確的步驟應該是什么,那將非常有幫助。 謝謝

到目前為止我的查詢:

select a.cust_id, a.code, b.cust_id as customer, b.code as product 
from a 
left join b on a.cust_id = b.cust_id and a.code = b.code

兩個條件:

  • cust_id 必須在表 B 中
  • (cust_id, code) 不得在表 B 中

帶有條件的查詢幾乎從人類語言翻譯成 SQL:

select *
from a
where cust_id in (select cust_id from b)
and (cust_id, code) not in (select cust_id, code from b);
  • 項目清單

  • 您好,其他使用存在的解決方案


select a.cust_id, a.code
  from TABLEA a  left   join TABLEB  b on 
      a.cust_id=b.cust_id and a.code=b.code
 where b.cust_id is null and exists( select * from TABLEB 
      where cust_id=a.cust_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM