Autor Zpráva
Kcko
Profil
Ahoj, řeším následující ...

jednoduchá tabulka test, hodnoty 1,2,3

Chci mít výstup
3
2
1
1
2
3
3
2
1


SELECT * FROM
(

(
  SELECT id FROM test ORDER BY id DESC
)

UNION ALL

(
  SELECT id FROM test ORDER BY id ASC
)

UNION ALL
(
  SELECT id FROM test ORDER BY id DESC
)

) as tmp


Výsledek

123 123 123 , tj. UNION nerespektuje seřazení v jednotlivých větvích. Výsledek je záměrně zjednoduššen jelikož reálná aplikace má samozřejmě složitější třídící mechanismy.
Nemá někdo tip co s tím? Všiml jsem si tohohle "bugu" až ted a to jsem s MySQL již nějaký ten pátek kamarád.
Tori
Profil
V manuálu jsem viděla dva údaje, které by se k tomu mohly vztahovat:

12.2.8: „If ORDER BY occurs within a subquery and also is applied in the outer query, the outermost ORDER BY takes precedence. For
example, results for the following statement are sorted in descending order, not ascending order:
(SELECT ... ORDER BY a) ORDER BY a DESC;“

12.2.8.3: „However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.“

Zkoušela jsem stejná data a když jsem si do jednotlivých větví doplnila limit 123456789, řadilo to už správně.
Kcko
Profil
Tori:
Excellent work! Kaju se za to, že jsem si to pořádně nepřečetl.

Vaše odpověď

Mohlo by se hodit

Odkud se sem odkazuje


Prosím používejte diakritiku a interpunkci.

Ochrana proti spamu. Napište prosím číslo dvě-sta čtyřicet-sedm:

0