我有以下表格,其中存盤了 suggestion_id 和 goal_id
。 。id|goal_id|suggestion_id
1 | 12| 1
2 | 13| 2
2| 17| 2
3 | 14| 1
4 | 15| 3
5 | 16| 3
6 | 12| 4
6| 18| 4
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我想查詢一個特定的 goal_ids 組合的 suggestion_id。
例如:
- goal_id(13, 17) => 我需要建議ID:2
- goal_id(12, 14) => 我需要的建議id:1 。
- goal_id(14, 12) => 我需要的建議id:1 。
- goal_id(12, 18) => 我需要的建議ID:4 。
這樣查詢 suggestion_id 是否可行,或者我必須重新設計我的表? (我使用的是PostgreSQL資料庫)
INPUT。(12, 14) 或 (14, 12) ID的順序可能會改變
select suggestion_id from table WHERE goal_id IN(12, 14) group by suggestion_id
查詢回傳以下id:1,1,4
uj5u.com熱心網友回復:
WHERE子句適用于單個行,而不是組。
IN本質上是WHERE goal_id = 12 OR goal_id = 14。
你需要的是第二個過濾器,它說但只有同時擁有這兩個的組
select suggestion_id
from table
where goal_id IN (12, 14)
group by suggestion_id
having count(distinct goal_id) = 2
HAVING子句是在聚合后應用于組。所以,現在我們可以計算組中有多少個不同的目標,并且只保留那些正好有兩個不同目標的組。
distinct是為了防止一個suggestion_id可以有相同的goal_id關聯到它一次以上。
注意:如果您的IN()串列有2個以上的專案,您也需要更新= 2。
uj5u.com熱心網友回復:
如果你想要子集匹配,并且正在尋找正好2個(或n項),那么Matt的答案是可行的。 然而,如果你想要整個匹配,例如12和14,而不是其他,那么我建議在這個方法上做一個改變。 假設該表沒有重復的內容:
select suggestion_id
from t
group by suggestion_id
having array_agg( goal_id order by goal_id) = array[12, 14]。
注意,使用陣列可以很容易地傳入任何數量的值。 你也可以對此進行調整,以使用陣列進行子集匹配:
select suggestion_id
from t
where goal_id = any(array[12, 14] )
group by suggestion_id
having array_agg( goal_id order by goal_id) = array[12, 14]
或者在這種情況下,你可以在having子句中使用陣列的長度:
having count(*) = cardinality(array[12, 14])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/324748.html
標籤:
