MySQL
ORDINATO DA
Ricerca…
contesti
Le clausole in un SELECT hanno un ordine specifico:
SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ...
ORDER BY ... -- goes here
LIMIT ... OFFSET ...;
( SELECT ... ) UNION ( SELECT ... ) ORDER BY ... -- for ordering the result of the UNION.
SELECT ... GROUP_CONCAT(DISTINCT x ORDER BY ... SEPARATOR ...) ...
ALTER TABLE ... ORDER BY ... -- probably useful only for MyISAM; not for InnoDB
Di base
ORDINA PER x
x può essere qualsiasi tipo di dati.
-
NULLsprecedono i non NULL. - Il valore predefinito è
ASC(dal più basso al più alto) - Le stringhe (
VARCHAR, ecc.) Sono ordinate secondo laCOLLATIONdella dichiarazione -
ENUMssono ordinati in base all'ordine di dichiarazione delle stringhe.
ASCending / DESCending
ORDER BY x ASC -- same as default
ORDER BY x DESC -- highest to lowest
ORDER BY lastname, firstname -- typical name sorting; using two columns
ORDER BY submit_date DESC -- latest first
ORDER BY submit_date DESC, id ASC -- latest first, but fully specifying order.
-
ASC=ASCENDING,DESC=DESCENDING -
NULLsvengono prima anche perDESC. - Negli esempi precedenti,
INDEX(x),INDEX(lastname, firstname),INDEX(submit_date)possono migliorare significativamente le prestazioni.
Ma ... Il mixaggio di ASC e DESC , come nell'ultimo esempio, non può utilizzare un indice composito a vantaggio. Né INDEX(submit_date DESC, id ASC) help - " DESC " è riconosciuto sintatticamente nella dichiarazione INDEX , ma ignorato.
Alcuni trucchi
ORDER BY FIND_IN_SET(card_type, "MASTER-CARD,VISA,DISCOVER") -- sort 'MASTER-CARD' first.
ORDER BY x IS NULL, x -- order by `x`, but put `NULLs` last.
Ordinazione personalizzata
SELECT * FROM some_table WHERE id IN (118, 17, 113, 23, 72)
ORDER BY FIELD(id, 118, 17, 113, 23, 72);
Restituisce il risultato nell'ordine di id specificato.
| id | ... |
|---|---|
| 118 | ... |
| 17 | ... |
| 113 | ... |
| 23 | ... |
| 72 | ... |
Utile se gli ID sono già ordinati e devi solo recuperare le righe.
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow