我有一个包含五个布尔列的表。
如何构造一个返回至少有2列为真的行的查询?
答案 0 :(得分:8)
将布尔类型转换为整数(0=false
,1=true
)并检查它们的总和:
select *
from my_table
where a::int + b::int + c::int + d::int + e::int >= 2;
答案 1 :(得分:2)
漫长的道路:
SELECT * from t where c1 and c2 or c1 and c3 or c1 and c4 or c1 and c5
or c2 and c3 or c2 and c4 or c2 and c5 or c3 and c4 or c3 and c5 or c4 and c5;
答案 2 :(得分:1)
只有在所有列都已定义NOT NULL
且尚未指定的情况下,才能使用已接受的答案。要使其与NULL
一起使用:
SELECT *
FROM tbl
WHERE (a IS TRUE)::int
+ (b IS TRUE)::int
+ (c IS TRUE)::int
+ (d IS TRUE)::int
+ (e IS TRUE)::int > 1;
或者:
SELECT *
FROM tbl
WHERE COALESCE(a::int, 0)
+ COALESCE(b::int, 0)
+ COALESCE(c::int, 0)
+ COALESCE(d::int, 0)
+ COALESCE(e::int, 0) > 1;