MySQL UNION with Multiple ORDER BY

MySQL

I have tried to make this work in multiple forms but none have been successful. I need to read an int from my table to order my data as desired. I have previously gotten this to work as multiple queries but Im hoping to do it all in one now.

    SELECT * FROM (
        (SELECT * FROM table_a WHERE int_a <= *myint* ORDER BY int_a DESC)
        UNION 
        (SELECT * FROM table_a WHERE int_a >= *myint* ORDER BY int_a DESC)
    ) uniontable

MySQL 5.7

Best Answer

I'm not exactly sure what you re trying to achieve, but if you want the rows from the first leg to be ordered first, then you can add an attribute that determines from which leg the row belongs:

select myint from (
    select 1 as origin, myint from table_a where myint < 5
    union
    select 2 as origin, myint from table_a where myint > 5
) as t
order by origin, myint desc;

myint
4
3
2
1
9
8
7
6

Fiddle