我有一个客户表 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
在这个例子中,cust_id
5000
没有从 t1
中拉出,因为关联的 cust_zip
89999
没有与 store_id
{{ 关联100
中的 1}}。这样做的最佳方法是什么?
答案 0 :(得分:1)
您是否尝试过简单的条件连接?
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 匹配
答案 1 :(得分:0)
听起来像是 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