Tony33 Tony33 - 5 months ago 12
MySQL Question

MySQL ORDER BY first field then second field

This is my actual query:

SELECT DISTINCT eventi.img AS img, posizione AS pos
FROM eventi
WHERE homepage =1
UNION
SELECT DISTINCT prodotti.img, prodotti.posizione
FROM prodotti
WHERE homepage =1
ORDER BY pos ASC


it returns positions like "1,1,2,2" . i want it returns positions by fields, like "event position 1,2 -> then products position 1,2" . Now it's mixing events and products positions...

Answer

You can do it like this:

SELECT t.img,t.pos FROM (
    SELECT DISTINCT 1 as order_col, eventi.img AS img, posizione AS pos
    FROM eventi
    WHERE homepage =1
    UNION
    SELECT DISTINCT 2 , prodotti.img, prodotti.posizione
    FROM prodotti
    WHERE homepage =1 ) t
ORDER BY t.order_col,t.pos

If you don't care about selecting the order_col then you can avoid the sub select and put the order by inside.

Comments