簡體   English   中英

SQL 查詢以查看是否滿足條件,僅此而已

[英]SQL query to see if condition is met and nothing else

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

在此處輸入圖片說明

我試圖找出列 anaID 的值是否為 22 或 23,並且沒有為該 subID/sampleID 組合的 anaID分配其他值

就像是

select * from anaData where subID='2020-04-21-17' and sampleID='crazy2' 
and 
(anaID=22 or anaID=23)
and 
andID <> ??anything else??

我可以查詢所有匹配項並循環遍歷它們並具有決定的程序邏輯,但我希望這可以在查詢中完成。

您可以使用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)中的anaID in (22, 23) exists會照顧到這一點。

如果至少存在一個 anaID 2223,這將起作用:

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

如果你想讓 2223 都切換到= 2 (假設組合subID/sampleID/anaID是唯一的。

這也可以在沒有 WHERE 條件的情況下使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM