[英]Select rows with the same foreign key but another column has a set of values
我設計了一個數據庫,該數據庫以這種格式存儲數據,其中兩列都是通向不同表的外鍵。 這是簡化版本。
RNA_id | Experiment_id |
1 | a |
1 | b |
2 | a |
2 | b |
2 | c |
3 | b |
4 | a |
4 | c |
我想選擇具有所有三個實驗ID的行。 在此示例中,結果應為
RNA_id | Experiment_id |
2 | a |
2 | b |
2 | c |
我試過了
GROUP BY RNA_id HAVING COUNT (DISTINCT Experiment_id)=3
但這只是導致我的行看似隨機而已。
數據庫已經很大,而且我的查詢已經相當復雜,此外,我可能想擴展到4個或更多的Experiment_id。
這是查詢的經過整理的版本,因為它很復雜,我不想解釋我的整個數據結構
我現有的查詢是:
SELECT RNA_id, Experiment_id, <data values>
FROM data
LEFT JOIN ref1
LEFT JOIN ref2
LEFT JOIN ref3
LEFT JOIN ref4
WHERE <required data parameters>
ORDER BY RNA_id
LIMIT 0,5000;
按應返回大約700個值,但是當我較早地將ORDER BY更改為該GROUP BY命令時,它返回9個值,所有這些值都具有唯一的RNA_id,應該返回大約100個值。
我的RNA_id實際上是3列,因此我可能只需要重做整個數據庫就可以使用這些解決方案。
我想通了如何使其與3列標識符一起使用
AND (RNA_id1, RNA_id2, RNA_id3) IN (SELECT RNA_id1, RNA_id2, RNA_id3
FROM data
WHERE <parameter>
GROUP BY RNA_id1, RNA_id2, RNA_id3
HAVING COUNT (DISTINCT Experiment_id)=3)
這也適用於不同數量的Experiment_id
我建議只返回具有所有三個的RNA_id
:
select RNA_id
from t
where Experiment_id in ('a', 'b', 'c')
group by RNA_id
having count(*) = 3;
如果可以重復,則使用count(distinct experiment_id)
。
如果需要原始行,則在MySQL 8+中,可以使用窗口函數來調整它:
select t.*
from (select t.*, count(*) over (partition by RNA_id) as cnt
from t
where Experiment_id in ('a', 'b', 'c')
) t
where cnt = 3;
SELECT *
FROM Table1 t1
WHERE ( SELECT COUNT(DISTINCT `Experiment_id`)
FROM Table1 t2
WHERE t2.`RNA_id` = t1.`RNA_id`
AND t2.Experiment_id in ('a', 'b', 'c') -- if you have more than 3 experiment
) = 3
如果a
, b
和c
是Experiment_id
的唯一可能值,則需要將查詢放入WHERE子句中,如下所示:
select *
from tablename
where RNA_id in (
select RNA_id from tablename
group by RNA_id
having count(distinct Experiment_id) = 3
)
如果還有其他值:
select *
from tablename
where
Experiment_id in ('a', 'b', 'c')
and RNA_id in (
select RNA_id from tablename
where Experiment_id in ('a', 'b', 'c')
group by RNA_id
having count(distinct Experiment_id) = 3
)
如果要擴展到三個以上的值,可以輕松更改這些查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.