我需要创建一条语句,以选择满足3个或更多条件的所有行。
高性能JS函数将使用此语句。
一条记录包含一些信息:foo
,bar
,baz
,qux
和fum
。
我想到了两种方法来做,我选择了一种对我来说似乎最好的方法,但是也许有更好的方法?
where
子句匹配3个或更多条件
我的意思是,例如,数据库必须返回3个字段或更多匹配的所有行。 下面有一个查询示例,有没有办法?我认为这很丑...如果我需要添加一些信息...
查询示例:
select * from MyTable
where (foo='foo1' and bar='bar1' and baz='baz1')
or (foo='foo1' and bar='bar1' and qux='qux1')
or (foo='foo1' and bar='bar1' and fum='fum1')
or (bar='bar1' and baz='baz1' and qux='qux1')
or (bar='bar1' and baz='baz1' and fum='fum1')
[other or for 3 conditions match ...]
or (foo='foo1' and bar='bar1' and baz='baz1' and qux='qux1')
or (foo='foo1' and bar='bar1' and baz='baz1' and fum='fum1')
or (foo='foo1' and bar='bar1' and qux='qux1' and fum='fum1')
[other or for 4 conditions match ...]
or (foo='foo1' and bar='bar1' and baz='baz1' and qux='qux1' and fum='fum1') /* 5 conditions match */
查询示例:
select * from MyTable
where foo='foo1' or bar='baz1' or baz='baz1' or qux='qux1'
您是否同意第一个提供最佳性能?如果是,还有更好的查询吗?
答案 0 :(得分:2)
SELECT
t.*
FROM mytable t
WHERE
(foo IS NOT DISTINCT FROM 'foo1')::int +
(bar IS NOT DISTINCT FROM 'bar1')::int +
(baz IS NOT DISTINCT FROM 'baz1')::int +
(qux IS NOT DISTINCT FROM 'qux1')::int +
(fum IS NOT DISTINCT FROM 'fum1')::int >= 3
IS NOT DISTINCT FROM
检查是否相等,并考虑NULL
答案 1 :(得分:0)
您可以检查以下查询
select * from
(
select a.*,
case when foo='foo1' then 1 else 0 end +
case when bar='baz1' then 1 else 0 end +
case when baz='baz1' then 1 else 0 end +
case when qux='qux1' then 1 else 0 end +
case when fum='fum1' then 1 else 0 end as total
from MyTable a
where foo='foo1' or bar='baz1' or baz='baz1' or qux='qux1' or fum = 'fum1'
) as a
where total>=3;