我需要创建一个语句来选择所有 mach 3 或更多条件的行。 此语句将由高性能 JS 函数使用。 一条记录有一些信息:foo
、bar
、baz
、qux
和fum
。 我想到了两种方法,我选择了在我看来最好的一种,但也许有更好的方法?
第一个(我认为最好的)
- 数据库运行
where
子句匹配 3 个或更多条件的语句我的意思是,例如,数据库必须返回 3 个或更多字段匹配的所有行。 下面是一个查询示例,有没有办法做到?我觉得这个很丑...如果我需要添加一些信息...
- 如果超过 1 条记录,则 JS 脚本确定好的记录(迭代结果)
查询示例:
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 */
另一个(我认为肯定是最糟糕的):
- DB 返回在一个条件下匹配的所有行
- 然后 JS 脚本通过迭代所有结果来确定好的
查询示例:
select * from MyTable
where foo='foo1' or bar='baz1' or baz='baz1' or qux='qux1'
你同意第一个提供最好的性能吗?如果是,有更好的查询吗?
demo:db<>fiddle
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
您可以查看以下查询
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;