且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 mysql 中使用 union 和 order by 子句

更新时间:2023-08-27 11:37:10

您可以通过向每个选择添加一个名为 rank 的伪列来实现此目的,您可以先按该列排序,然后再按其他条件排序,例如:

You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:

select *
from (
    select 1 as Rank, id, add_date from Table 
    union all
    select 2 as Rank, id, add_date from Table where distance < 5
    union all
    select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc