【问题标题】:how to optimize union in SQL如何在 SQL 中优化联合
【发布时间】:2019-12-15 17:52:31
【问题描述】:

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

听说过早优化是万恶之源,但我想提高我对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 以避免昂贵的重复数据删除,而您的查询不会发生这种情况
  • 我认为第一个查询没用。第一个返回的任何内容也将包含在第二个中。
  • 主要是我想将第一个查询中的内容排序到顶部。有没有更好的排序方法,以便使用 '%happy'% 将完全匹配放置在部分匹配之上
  • 你可以使用像... and t.title ~~* any(array['%happy%', '%birthday%']) order by t.title ~~* all(array['happy', 'birthday']) desc 这样的东西,它会首先返回完全匹配的那些
  • 哦,那太酷了。那我试试看

标签: sql postgresql optimization


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多