2016-12-13 33 views
0

我想写一个查询来选择行,使条件严格满足。我想通过一个例子来展示我想要做的最好的方式。MySQL使用“只有当”条件选择行

假设我有如下表

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

我想的是,返回只匹配给定值的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,因为在运营商满意只是ID为1的值1,我不知道如何执行“严格”部分。

回答

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 
+0

他y @戈登,好东西!我还没有了解在子句中使用列对比的方式。虽然你不愿意使用count而不是sum,那么允许使用负值吗? – Anand

+1

它是对一个布尔表达式进行求和,所以只有1或0会相加,因此没有负数。 (编辑:我刚刚用数字试过,但没有奏效)。 – McAngus

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