从条件获取mysql表中的特定行

问题描述 投票:-1回答:3

我有下面提到的表:

ID     Value
KA-1   A
KA-1   B
KA-1   C
KA-1   D
KA-2   A
KA-2   C
KA-2   C
KA-2   D
KA-3   C
KA-3   B

我想取这些ID,其中至少有一个对应的值是D但是相同的ID没有值B

要求输出:

ID
KA-2
mysql
3个回答
2
投票

一个简单的解决方案是:

select distinct id from table
   where value='D' and id not in (select distinct id from table where value='B')

2
投票
SELECT ID
FROM YOUR_TABLE
GROUP BY ID
HAVING SUM(VALUE='D')>=1 AND SUM(VALUE='B')=0;

看到一个有效的DEMO on SQL Fiddle


1
投票

您可以尝试使用exists而不存在:

select id 
from table1 as a
where exists (select *
              from table1 b
              where b.value='D' and b.id=a.id)
      and not exists (select *
              from table1 c
              where c.value='B' and c.id=a.id)
© www.soinside.com 2019 - 2024. All rights reserved.