简体   繁体   English

如何从A表中选择B表中不存在的值?

[英]How to choose values from A table which are absent in B table?

I have 2 tables in mySQL DB: A & B. 我在mySQL DB中有2个表:A和B.

a, b, c columns. a,b,c列。

Table A: 表A:

 a(1) = 1 
 a(2) = 2
 a(3) = 3

Table B: 表B:

 a(1) = 1 
 a(2) = 2

So, we could see that in B table there is no row with a = 3. How could I request DB to find it? 所以,我们可以看到在B表中没有a = 3的行。我怎么能请求DB找到它?

So response (one row) could looks like: 所以响应(一行)可能看起来像:

a(1) = 3 
b(1) =..
c(1) =.. 

One option uses EXISTS : 一个选项使用EXISTS

SELECT a.a
FROM TableA a
WHERE NOT EXISTS (SELECT 1 FROM TableB b WHERE b.a = a.a);

Another option would be to do an anti-join: 另一种选择是进行反加入:

SELECT a.a
FROM TableA a
LEFT JOIN TableB b
    ON a.a = b.a
WHERE b.a IS NULL;

You can also give up joins and use WHERE and nested SELECT: suppose TabA holds values of 1,2,3 in subsequent rows of column ValA and TabB holds values of 1,2 in subsequent rows of column ValB and you want only a row containing value of 3 from TabA you can do this without joins: 您也可以放弃连接并使用WHERE和嵌套SELECT:假设TabA在ValA列的后续行中保存1,2,3的值,并且TabB在ValB列的后续行中保存值1,2并且您只需要包含一行来自TabA的值为3,您可以在没有连接的情况下执行此操作:

SELECT  Val_A
FROM TabA  
WHERE Val_A NOT IN (SELECT Val_B FROM TabB)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM