![](/img/trans.png)
[英]How to select all records from one table that do not exist in another table for certain condition in another table?
[英]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_id
、 t2.cust_zip
和t1.cust_id
一個表中,其中:
cust_zip
字段匹配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.