【发布时间】: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