我有一个如下所示的MySQL表:
我要查找的是anaID列的值是22还是23,并且对该子ID / sampleID组合的anaID 没有分配其他值。
类似
src/test/kotlin
我可以查询所有匹配项并循环遍历,并具有决定的程序逻辑,但是我希望可以在查询中完成。
答案 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条件的情况下使用。