MySQL
ORDEN POR
Buscar..
Contextos
Las cláusulas en un SELECT tienen un orden específico:
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
BASIC
ORDEN POR x
x puede ser cualquier tipo de datos.
-
NULLspreceden a los que no son NULL. - El valor predeterminado es
ASC(de menor a mayor) - Las cadenas (
VARCHAR, etc.) se ordenan de acuerdo con laCOLLATIONde la declaración -
ENUMsson ordenados por la orden de declaración de sus cadenas.
Ascendiendo descendiendo
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 -
NULLsson los primeros incluso paraDESC. - En los ejemplos anteriores,
INDEX(x),INDEX(lastname, firstname),INDEX(submit_date)pueden mejorar significativamente el rendimiento.
Pero ... Mezclar ASC y DESC , como en el ejemplo anterior, no puede usar un índice compuesto para beneficiarse. Tampoco lo ayudará INDEX(submit_date DESC, id ASC) - " DESC " se reconoce sintácticamente en la declaración INDEX , pero se ignora.
Algunos trucos
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.
Pedidos personalizados
SELECT * FROM some_table WHERE id IN (118, 17, 113, 23, 72)
ORDER BY FIELD(id, 118, 17, 113, 23, 72);
Devuelve el resultado en el orden especificado de ID.
| carné de identidad | ... |
|---|---|
| 118 | ... |
| 17 | ... |
| 113 | ... |
| 23 | ... |
| 72 | ... |
Es útil si los identificadores ya están ordenados y solo necesita recuperar las filas.
Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow