2016-08-17 45 views
0

我很感激任何关于如何在SQL中检查一个列表中的元素是否也出现在另一个列表中的指针。SQL检查一个列表与另一个

List A = Live Customers in April 
List B = Live Customers in May 

如何检查列表B中的哪些客户也出现在列表B中?以识别那些已经丢失的客户

i.e. Customers in A but not in B. 

谢谢你的帮助。 GAV

+2

有很多方法可以解决这个问题,但是如果您想要一个可操作的答案,您需要向我们展示一些表结构。 –

+1

也请提及您正在使用的RDBMS,如SQLServer,Oracle,MySQL,Postgre .. – TheGameiswar

+0

SQL标准定义了“INTERSECT”和“EXCEPT”[设置运算符](https://en.wikipedia.org/wiki/Set_operations_(SQL )),但不是所有的DBMS都能实现它们。但如前所述,这取决于您使用的数据库供应商和版本。 – GarethD

回答

0

尝试not in条款

例如

select * 
from mytable 
where id not in (select id from table2) 

这会返回结果不在另一个表。快速和简单的

+0

检查这个答案的影响不在:http://stackoverflow.com/questions/173041/not-in-vs-not-exists – TheGameiswar

1

不同的方法来拉动的结果

SELECT customer 
FROM ListA a 
WHERE NOT EXISTS (SELECT 1 FROM ListB b WHERE a.customer=b.customer) 

OR

SELECT a.customer 
FROM ListA a 
    LEFT JOIN ListB b ON a.customer=b.customer 
WHERE b.customer is null 

OR

SELECT customer 
FROM ListA 

except 

SELECT customer 
FROM ListB 

OR

SELECT customer 
FROM ListA 
WHERE customer NOT IN (SELECT customer FROM ListB)