表1:选定人员
id|name|date|rating
表2:人员
id|name|date|rating
我想构建一个查询,该查询将按desc顺序对所有选择的人员按日期从table 1
的顺序返回,所有table 2
人按顺序排序。
如果表1中有3个人,表2中有4个人,则查询应返回按日期顺序排列的前3个所选人作为前3个条目,然后返回按等级排序的4人条目。 如何使用sql实现此目的?
答案 0 :(得分:2)
这是一种适用于大多数数据库的方法:
select id, name, date, rating
from ((select id, name, date, rating, 1 as which
from table1
) union all
(select id, name, date, rating, 2 as which
from table1
)
) t
order by which,
(case when which = 1 then date end),
rating
答案 1 :(得分:1)
我认为您想要
select id, name, date, rating
from (
select id, name, date, rating, 't1' which from table1
union all
select id, name, date, rating, 't2' which from table2
)
order by
case when which = 't1' then date end desc,
rating end desc
子查询使用union all
从两个表中进行选择,并带有一个附加列,该列指示每个记录来自哪个表。然后,外部查询进行条件排序:
case
表达式返回date
的{{1}},否则返回t1
;因此,降序排序将null
t2 t1 rows first, ordered by descending dates (rows from
null`(按降序排列在最后)放在空位。
第二个排序标准对其余行进行排序(即来自get
评分的行
在MySQL中,这可以缩短一点:
t2 by descending
答案 2 :(得分:0)
这是Union的用例。尝试以下查询:
SELECT id, name, date, rating FROM table1
ORDER BY date DESC
UNION
SELECT id, name, date, rating FROM table2
ORDER BY rating DESC