【问题标题】:sql how to sort by a union's subquery without adding a column?sql如何在不添加列的情况下按联合子查询排序?
【发布时间】:2019-08-09 10:42:32
【问题描述】:

所以我主要有我需要的查询,但我注意到我仍然从第一个选择和第二个选择中得到重复。我认为使用 UNION 而不是 UNION ALL 会删除重复项,但是因为它们具有不同的序列号,所以它们不会被删除。如何在不添加不必要的 seq 列的情况下通过 select 语句对结果进行排序?

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

【问题讨论】:

  • 没有重复,因为第一列在一个表中是 1,在另一个表中是 2。

标签: sql postgresql


【解决方案1】:

您可以使用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;

【讨论】:

  • 这种表达式的排序似乎在单个表中有效,但不适用于联合的排序依据。我是否需要以某种方式为联合命名才能引用它而不是模板 t?
  • 发现只需要命名子查询。对不起,我还是个菜鸟。这个世界要学的东西太多了
猜你喜欢
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 2023-04-06
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多