我读到最好在数据库端进行排序而不是将其全部加载到内存中,但我觉得可以做很多事情来改进这一点。我只是使用联合来订购各种查询。这是一种不好的方法,我应该做些什么来优化查询吗?
听说过早优化是万恶之源,但我想提高我对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