MySQL使用“仅当”条件选择行

时间:2016-12-13 19:39:34

标签: mysql sql database

我正在尝试编写一个查询来选择行,以便严格满足条件。我认为展示我想要做的最好的方法就是举个例子。

假设我有下表

+------------+
| A_Table    |
+----+-------+
| id | value |
+----+-------+
|  1 |     1 |
|  2 |     1 |
|  2 |     2 |
|  3 |     1 |
|  3 |     2 |
|  3 |     5 |
+----+-------+

我想要的是一个返回仅匹配给定值的id的查询。例如,假设我希望id的值严格在(1,2)中,id = 2是唯一满足此要求的id。尽管id = 3的值为1和2,但它并不严格只有那些值(以及id = 1)。

以下是我提出的查询

select id
from A_Table a
where value in (1,2)
and not exists (
  select b.id 
  from A_Table b
  where value not in (1,2)
  and b.id = a.id
);

但是这会返回1和2,因为in运算符只满足id 1的值1.我不确定如何强制执行“strict”部分。

3 个答案:

答案 0 :(得分:1)

我会使用聚合来做到这一点:

select a.id
from a_table a
group by a.id
having sum(a.value = 1) > 0 and         -- id has value = 1
       sum(a.value = 2) > 0 and         -- id has value = 2
       sum(a.value not in (1, 2)) = 0;  -- id has nothing else

答案 1 :(得分:0)

您可以使用group by之类的

select id
from tbl1
group by id
having count(distinct value) = 2;

这是一个演示:http://sqlfiddle.com/#!9/b1b23/1

答案 2 :(得分:0)

我的建议:

select id
from A_table as a
where exists (
    select 1
    from A_Table
    where value in (1, 2)
    and id = a.id
    )
and not exists (
    select 1
    from A_Table
    where value not in (1, 2)
    and id = a.id
    )
group by id