postgrehow to optimization programming 中的联合



我读到最好在数据库端排序而不是将其全部加载到内存中,但我觉得可以做很多事情来改善这一点。我只是使用联合来排序各种查询。这是一种糟糕的方法,我应该做一些事情来优化查询吗?

我听说过早的优化是万恶之源,但我想提高我对 sql 的了解

select 1 as seq, t.* from template t
join template_type_link ttl on ttl.template_idx = t.idx 
WHERE status = 'ACTIVE'  
and
t.title in all(array['happy', 'birthday']) 
UNION
select 2 as seq, t.* from template t
join template_type_link ttl on ttl.template_idx = t.idx 
WHERE status = 'ACTIVE'  
and
t.title ~~* any(array['%happy%', '%birthday%']) 
UNION
select 3 as seq, t.*  from template t 
join template_type_link ttl on ttl.template_idx = t.idx 
WHERE status = 'ACTIVE'  
and
t.idx in (select template_idx from template_keyword where keyword in ('happy', 'birthday' ))      
order by seq asc

你的技术会起作用,只是它应该是UNION ALL而不是UNION

但是,如果您只需要按顺序排列四个结果集,其中每个结果集中的顺序无关紧要,则最好只一个接一个地运行四个单独的查询。这将避免排序,这可能非常昂贵。如果结果行很多,则此方法可能会获胜。

如果结果行很少,则成本可能由客户端-服务器往返次数决定,并且您的原始方法可能会胜出。

尝试两者并进行比较,看看什么更适合您。

最新更新