我可以对从不同WHERE子句获得的结果进行排名吗?

问题描述 投票:0回答:2

假设我想选择包含特定标签或与关键字匹配的帖子。

select t1.*
from (
select p.*, count(p.id) from plainto_tsquery('hElLo') AS q , post p 
left join post_tag pt on pt.post_id = p.id
left join tag t on t.id = pt.tag_id
WHERE (tsv @@ q) or t.id in (2,3)
group by p.id
) as t1 
order by count desc, ts_rank_cd(t1.tsv, plainto_tsquery('hElLo')) desc 
limit 5;

以上确实选择了我想要的。在tsv,我给了title A重量和description D重量。当按count排序时,它现在变得毫无意义,因为每个条目具有相同的权重。是否有可能做这样的事情,比如如果从t.id in (2,3)挑选这一行,他们将排序到第一行,然后按ts_rank_cd排序,或者给每个匹配标签'A'重量,标题变成B重量,描述是D?

postgresql
2个回答
1
投票

试试CASE WHEN

select t1.*
from (
select p.*, count(p.id), 
(CASE WHEN t.id in (2,3) THEN 1 ELSE 2 END) as ranking 
from plainto_tsquery('hElLo') AS q , post p 
left join post_tag pt on pt.post_id = p.id
left join tag t on t.id = pt.tag_id
WHERE (tsv @@ q) or t.id in (2,3)
group by p.id
) as t1 
order by count desc, ranking asc, ts_rank_cd(t1.tsv, plainto_tsquery('hElLo')) desc 
limit 5;

编辑(正确答案):

select t1.*
from (
select p.*, count(p.id), 
COUNT(1) filter(where t.id in (2,3)) ranking
from plainto_tsquery('hElLo') AS q , post p 
left join post_tag pt on pt.post_id = p.id
left join tag t on t.id = pt.tag_id
WHERE (tsv @@ q) or t.id in (2,3)
group by p.id
) as t1 
order by count desc, ranking asc, ts_rank_cd(t1.tsv, plainto_tsquery('hElLo')) desc 
limit 5;

0
投票

我不确定为什么计数会相同,但你可以添加更多的密钥到order by

order by count desc,
         (t.id in (2, 3)) desc,
         ts_rank_cd(t1.tsv, plainto_tsquery('hElLo')) desc ;

desc是因为true> false,你想要真正的值是第一位的。

© www.soinside.com 2019 - 2024. All rights reserved.