繁体   English   中英

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

[英]MySQL Select row using “only if” condition

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

假设我有下表

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

我想要的是返回仅与给定值匹配的ID的查询。 例如,说我希望id的值严格在(1,2)中,id = 2是唯一满足此要求的值。 即使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”部分。

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

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

您可以group by喜欢使用group by

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

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

我的建议:

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

暂无
暂无

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

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