SQL查询,看是否满足条件

时间:2020-09-10 20:24:28

标签: mysql sql

我有一个如下所示的MySQL表:

enter image description here

我要查找的是anaID列的值是22还是23,并且对该子ID / sampleID组合的anaID 没有分配其他值

类似

src/test/kotlin

我可以查询所有匹配项并循环遍历,并具有决定的程序逻辑,但是我希望可以在查询中完成。

2 个答案:

答案 0 :(得分:1)

您可以使用not exists

select *
from anaData a
where subID = '2020-04-21-17' and
      sampleID = 'crazy2' and
      not exists (select 1
                  from anaData a2
                  where a2.subID = a.subID and a2.sampleID = a.sampleID and
                        a2.anaID not in (22, 23)
                 );

事实证明,外部查询中不需要anaID in (22, 23)exists会解决这个问题。

答案 1 :(得分:1)

如果至少存在一个anaID 22 23,这将起作用:

select subID, sampleID
from anaData 
where subID='2020-04-21-17'
  and sampleID='crazy2' 
group by subID, sampleID
having
   sum(case when anaID in (22, 23) then 1 else -100 end) > 1

如果您想同时将22 23都切换到= 2(假设 subID / sampleID / anaID 组合是唯一的。

这也可以在没有WHERE条件的情况下使用。