[英]SQL Create Statement for Multiple Columns Containing all Given Values
我有一個PostgreSQL數據庫。 我要問的是當我有一個表時,其中A
, B
和C
是列名,其他數字是值:
A | B | C
---------
0 | 1 | 2
1 | 2 | 3
2 | 1 | 3
0 | 3 | 2
我的搜索要求該行必須包含1
和3
,有效行將是第2行和第3行,因為它們都具有兩個值。 有沒有比使用大量IN
運算符創建大型嵌套查詢更簡單的方法?
只需使用兩個in
語句:
select *
from table t
where 1 in (A, B, C) and 3 in (A, B, C);
似乎像這樣的事情可能會起作用。(未測試)
Select tn.*, case when 1 in (a,b,c) then 1 end as isOne,
case when 3 in (a,b,c) then 1 end as isThree
FROM tableName tn
having isOne = 1 and isThree=1
要么
with cte (Select tn.*, case when 1 in (a,b,c) then 1 end as isOne,
case when 3 in (a,b,c) then 1 end as isThree
FROM tableName tn)
SELECT * from CTE where isOne = 1 and isThree=1
我不確定是否可以正確評估。
@GordonLindoff的答案適用於測試相等性。 但是,如果必須使用LIKE,則必須使用常規邏輯:
WHERE ((A LIKE '%1%' AND (B LIKE '%3%' OR C LIKE '%3%'))
OR (B LIKE '%1%' AND (A LIKE '%3%' OR C LIKE '%3%'))
OR (C LIKE '%1%' AND (A LIKE '%3%' OR B LIKE '%3%')))
請記住,考慮到LIKE的運行方式,這可能效率很低。
您可以從每一行創建一個數組,並檢查這些數組是否與[1,3]重疊:
SELECT a, b, c FROM t WHERE ARRAY[1,3] <@ ARRAY[a,b,c]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.