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

Sql 根据条件从一个表中选择不在另一个表中的所有记录,sql,hive,Sql,Hive,我有一个customers表t1,如下所示: cust_id cust_zip 1000 19999 2000 29999 4000 39999 5000 89999 store_id cust_id cust_zip 100 1000 19999 100 2000 29999 100 3000 39999 我

我有一个customers表
t1
,如下所示:

cust_id    cust_zip
   1000      19999
   2000      29999
   4000      39999
   5000      89999
store_id    cust_id    cust_zip
     100       1000       19999
     100       2000       29999
     100       3000       39999
我有一个事务表
t2
,如下所示:

cust_id    cust_zip
   1000      19999
   2000      29999
   4000      39999
   5000      89999
store_id    cust_id    cust_zip
     100       1000       19999
     100       2000       29999
     100       3000       39999
我试图将
t2.store\u id
t2.cust\u zip
t1.cust\u id
拉到一个表中,其中:

  • cust\u zip
    字段匹配
  • 客户id
    字段不匹配
  • 我想要的结果是:

    store_id    cust_zip    cust_id
         100       39999       4000
    

    在此示例中,不会从
    t1
    中提取
    cust\u id
    5000
    ,因为关联的
    cust\u zip
    89999
    t2
    中的
    存储id
    100没有关联。最好的方法是什么?

    听起来像是连接和WHERE查询。类似这样的情况:(根据您的SQL方言,查询可能会有所不同)


    你试过简单的条件连接吗

    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
    
    选择t2.store\u id,t2.cust\u zip,t1.cust\u id
    从t2开始
    在t2.cust\u zip=t1.cust\u zip和t2.cust\u idt1.cust\u id上连接t1
    

    我确实想知道为什么你的数据库没有标准化。我认为交易表可能有store_zip,然后您尝试将store zip与customer zip进行匹配,重复
    t1.cust_zip=t2。cust_zip
    条件是不必要的。您甚至可以不使用
    WHERE
    子句,只需添加
    和t1.cust\u id!=t2.将客户id
    添加到ON子句中。