我读到在数据库端排序比将其全部加载到内存中更好,但我觉得可以做很多事情来改进这一点。我只是使用 union 来订购各种查询。这是一种糟糕的方法吗?我应该做些什么来优化查询吗?
听说过早优化是万恶之源,但我想提高自己的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
。
但是如果您只需要四个顺序的结果集,而每个结果集中的顺序无关紧要,那么您最好依次运行四个单独的查询。这将避免排序,这可能非常昂贵。如果有很多结果行,这种方法可能会获胜。
如果结果行很少,成本可能主要由客户端-服务器往返次数决定,您的原始方法可能会获胜。
同时尝试和基准测试,看看哪个更适合您。
关于sql - 如何在 SQL 中优化联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405479/