简体   繁体   中英

sql how to sort by a union's subquery without adding a column?

So I mostly have the query I need, but I noticed that I still get duplicates from the first select and the second select. I thought that using UNION instead of UNION ALL would remove duplicates, but because they have a different sequence number they are not removed. How can I order my results by the select statement without adding an unnecessary seq column?

select 1 as seq, t.* from template t 
WHERE status = 'ACTIVE' and t.title ~* '.*동\s*아\s*리\s*로\s*고\s*.*' 
UNION 
select 2 as seq, t.* from template t 
WHERE status = 'ACTIVE' and t.title ~* any(array['.*동\s*아\s*리\s*로\s*고\s*.*']) 
UNION select 3 as seq, t.* from template t WHERE status = 'ACTIVE' 
order by seq asc

You can do this using order by :

select t.*
from template t 
where status = 'ACTIVE' 
order by (t.title ~* '.*동\s*아\s*리\s*로\s*고\s*.*') desc,
         (t.title ~* any(array['.*동\s*아\s*리\s*로\s*고\s*.*']) desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM