根据条件从一个表中选择不在另一个表中的所有记录

时间:2021-03-03 19:16:11

标签: sql hive

我有一个客户表 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

在这个例子中,cust_id 5000 没有从 t1 中拉出,因为关联的 cust_zip 89999 没有与 store_id {{ 关联100 中的 1}}。这样做的最佳方法是什么?

2 个答案:

答案 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