mysql查询从一个表中选择,使其列的值不存在于另一个表

时间:2015-10-29 09:29:30

标签: mysql

我有两个mysql表:A和B。

A有列id,alpha,blabla,moreblabla,主键ID。 B有列id,alpha,beta,somemoreblabla,主键(id,alpha)

我需要选择所有那些A.id's,其A.alpha不存在于每个B.id = A.id

中的任何B.alpha中。

我该怎么做?

4 个答案:

答案 0 :(得分:1)

你的问题并不完全清楚。你想要所有不在任何B.alpha的A.alpha吗?在这种情况下,这样的简单查询就足够了:

Select A.id from A where A.alpha NOT IN (Select B.alpha from B);

如果你想从A中选择所有在B中具有对应物(相同ID)的ID,但是A和B之间的α不同,则需要更多工作:

SELECT A.id FROM A
INNER JOIN B on A.id = B.id
WHERE A.alpha != B.alpha

考虑以下结构:

CREATE TABLE `A` (
`id` int(11) NOT NULL,
`alpha` varchar(255) NOT NULL
);

CREATE TABLE `B` (
`id` int(11) NOT NULL,
`alpha` varchar(255) NOT NULL
);

使用插入:

insert into A set id = 1, alpha = 'a';
insert into A set id = 2, alpha = 'b';
insert into B set id = 1, alpha = 'a';
insert into B set id = 2, alpha = 'a';

如果您使用联接运行查询,结果将是:

+----+
| id |
+----+
|  2 |
+----+

这是因为A中的ID 2与B中的ID 2具有不同的alpha。

编辑:

我刚想到你甚至可能意味着每个A.id可以多次出现在B中。如果这是可能发生的事情,您需要再次采用不同的方法。让我们假设与以前相同的插入添加:

insert into A set id = 1, alpha = 'a';
insert into A set id = 2, alpha = 'b';
insert into B set id = 1, alpha = 'a';
insert into B set id = 2, alpha = 'a';

insert into B set id = 2, alpha = 'b'; <- important since there is now a 2nd 2 in B that should ensure that the record with ID 2 from A should not be returned.

insert into A set id = 3, alpha = 'c';
insert into B set id = 3, alpha = 'x'; <-- only ID 3 should now be returned due to the situation above

我们的表现在看起来像这样:

A
+----+-------+
| id | alpha |
+----+-------+
|  1 | a     |
|  2 | b     |
|  3 | c     |
+----+-------+

B
+----+-------+
| id | alpha |
+----+-------+
|  1 | a     |
|  2 | a     |
|  2 | b     |
|  3 | x     |
+----+-------+

如果是这种情况,以下查询将起到作用:

select A.id 
FROM A where A.alpha NOT IN (
    select B.alpha FROM B where B.id = A.id
);

答案 1 :(得分:1)

SELECT A.id
FROM
A 
LEFT OUTER JOIN B  ON A.id = B.id AND B.alpha = A.alpha
where B.alpha IS NULL

Here是SQL Fiddle

这将是最快的查询,在查询优化方面优于The marked Answer

EXPLAIN SELECT A.id
        FROM
        A 
        LEFT OUTER JOIN B  ON A.id = B.id AND B.alpha = A.alpha
        where B.alpha IS NULL

Here是输出:enter image description here

EXPLAIN select A.id 
FROM A where A.alpha NOT IN (
    select B.alpha FROM B where B.id = A.id
)

HereEXPLAIN的{​​{1}}。

enter image description here

你可以看到差异。

  

Marked answer VS SIMPLE

     

PRIMARY VS SIMPLE

希望这有帮助。

答案 2 :(得分:0)

Select A.id from table_A where A.alpha NOT IN (Select B.alpha from table_B);
子查询将返回一个表,其中包含来自table_B的所有B.alpha记录。 并说它返回1到5条记录作为结果。 并说你的table table_A在A.alpha中有1到10条记录 现在,您的父查询将检查表table_A中的字段A.alpha中不属于B.alpha的记录(使用NOT IN) 因此预期的结果是6到10。

答案 3 :(得分:0)

使用MySQL NOT IN 试试这个问题: -

select id from a where a.id NOT IN (select id from b)