我需要按正确的 OR 子句的数量对 PostgreSQL 查询的结果进行排序/排名。例如,给定一个查询,如
SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC
应根据满足条件的数量对结果进行排名。也非常欢迎使用视图/存储过程解决此问题的方法!
我需要按正确的 OR 子句的数量对 PostgreSQL 查询的结果进行排序/排名。例如,给定一个查询,如
SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC
应根据满足条件的数量对结果进行排名。也非常欢迎使用视图/存储过程解决此问题的方法!
重复条件并添加它们:
SELECT * FROM mytable
WHERE fld = 'A' OR fldB = CURRENT_DATE OR fldC = 7
ORDER BY
(fld = 'A')::int + (fldB = CURRENT_DATE)::int + (fldC = 7)::int
DESC
可能是这样的:
select *
from (
SELECT * , case when cond1 then 1 else 0 end
+ case when cond2 then 1 else 0 end
+ case when cond3 then 1 else 0 end as cond_count
FROM mytable
WHERE cond1
OR cond2
OR cond3
) t
order by cond_count desc
这个解决方案的丑陋之处在于你在语句中每个条件都有两次,但我现在想不出另一种解决方案。
The above query will check those conditions from the left side one by one i.e
if the cond1 is true then
return the results order by rank.
if cond1 is false and cond2 is true then
return the results order by rank.
if cond1 and cond2 both are false but cond3 is true
returns the results order by rank.
if all conditions are false then no result is returned.
So in brief it doesn't check all the conditions simultaneously for OR conditions.
Thanks.