我想你想要
order by
和
fetch first row
:
select t.*
from t
where user_id = 12 and
(type_id = 3 or type_id is null) and
(task_id = 2 or task_id is null) and
(source_id = 1 or source_id is null) and
(target_id = 2 or target_id is null)
order by ( (type_id is not null)::int +
(task_id is not null)::int +
(source_id is not null)::int +
(target_id is not null)::int
) desc
fetch first 1 row only;
这将返回与您的条件匹配的行,但最少
NULL
值(即最具体的行)。
编辑:
如果需要按顺序匹配它们,则
where
子句如下所示:
order by (type_id is not null)::int desc,
(task_id is not null)::int desc,
(source_id is not null)::int desc,
(target_id is not null)::int desc