簡體   English   中英

Select 基於條件的一個表中的所有記錄,而不是另一個表中的所有記錄

[英]Select all records from one table not in another table based on a condition

我有一個如下所示的客戶表t1

cust_id    cust_zip
   1000      19999
   2000      29999
   4000      39999
   5000      89999

我有一個看起來像這樣的事務表t2

store_id    cust_id    cust_zip
     100       1000       19999
     100       2000       29999
     100       3000       39999

我正在嘗試將t2.store_idt2.cust_zipt1.cust_id一個表中,其中:

  1. cust_zip字段匹配
  2. cust_id字段不匹配

我正在尋找的結果是:

store_id    cust_zip    cust_id
     100       39999       4000

在此示例中,未從t1提取cust_id 5000 ,因為關聯的cust_zip 89999未與t2中的store_id 100關聯。 最好的方法是什么?

您是否嘗試過簡單的條件連接?

Select t2.store_id,t2.cust_zip,t1.cust_id
from t2
join t1 on t2.cust_zip=t1.cust_zip and t2.cust_id<>t1.cust_id

我確實想知道為什么您的數據庫沒有標准化。 我認為事務表可能有 store_zip 然后您嘗試將存儲 zip 與客戶 zip 匹配

聽起來像是一個 JOIN 和一個 WHERE 查詢。 像這樣:(查詢可能會有所不同,具體取決於您的 SQL 方言)

SELECT t2.store_id, t2.cust_zip, t1.cust_id FROM t1
JOIN t2 ON t1.cust_zip = t2.cust_zip
WHERE t1.cust_zip = t2.cust_zip AND
      t1.cust_id != t2.cust_id

暫無
暫無

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

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