Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL UNION ORDERING

Tags:

sql

mysql

Is it possible to order the first enquiry and keep the rows returned as first and not order the second enquiry. (If that makes sence)

An example of my current enquiry is :

SELECT
    *
FROM 
    Devices
WHERE
    Live = 'true'
    AND Category = 'apple'
ORDER BY
    ListOrder
UNION
SELECT
        *
    FROM
        Devices
    WHERE
        DeviceLive = 'true'

I was hoping that the devices under the category apple would be organised in there list order and would be at the top of the list above the other devices. But this seems to jumble the two querys together.

like image 706
Yardstermister Avatar asked Nov 24 '10 14:11

Yardstermister


1 Answers

You'd need to introduce an artificial sort key. Something like:

SELECT
    *, 1 as SortKey
FROM 
    Devices
WHERE
    Live = 'true'
    AND Category = 'apple'
UNION
SELECT
        *, 2 as SortKey
    FROM
        Devices
    WHERE
        DeviceLive = 'true'
ORDER BY SortKey, ListOrder
like image 112
Joe Stefanelli Avatar answered Nov 15 '22 18:11

Joe Stefanelli