3

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

听说过早优化是万恶之源,但我想提高我对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
4

1 回答 1

1

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

但是,如果您只需要按顺序排列四个结果集,而每个结果集中的顺序并不重要,那么您最好一个接一个地运行四个单独的查询。这将避免排序,这可能非常昂贵。如果有很多结果行,这种方法可能会赢。

如果只有很少的结果行,则成本可能主要取决于客户端-服务器往返次数,而您的原始方法可能会胜出。

尝试两者并进行基准测试,看看什么更适合您。

于 2019-08-08T05:56:58.380 回答