Mysql
 sql >> Database >  >> RDS >> Mysql

MySQL Ordina per campi e genitori

È meglio mantenere parent_id ma non il nome del genitore.

Ecco una soluzione rapida per ordinare il tuo tavolo http://sqlfiddle.com/#!9/2a1fb /3

SELECT *
FROM table1
ORDER BY 
   CASE WHEN parent_id IS NULL THEN CAST(ID AS CHAR)
   ELSE CONCAT(CAST(parent_id AS CHAR),'-', CAST(ID AS CHAR)) END

MODIFICA 1 Variante #2 :-) http://sqlfiddle.com/#!9/76dcb/23

SELECT t1.* 
FROM table1 t1
LEFT JOIN table1 t2
ON t2.ID = t1.parent_id
ORDER BY 
   CASE WHEN t2.ord_idx IS NULL THEN CAST(t1.ord_idx AS CHAR)
   ELSE CONCAT(CAST(t2.ord_idx AS CHAR),'-',CAST(t1.ord_idx AS CHAR)) END

MODIFICA 2 per vedere come funziona questo ordine puoi semplicemente aggiungere questo campo per selezionare parti come:

SELECT t1.*, CASE WHEN t2.ord_idx IS NULL THEN CAST(t1.ord_idx AS CHAR)
   ELSE CONCAT(CAST(t2.ord_idx AS CHAR),'-',CAST(t1.ord_idx AS CHAR)) END as my_order 
FROM table1 t1
LEFT JOIN table1 t2
ON t2.ID = t1.parent_id
ORDER BY 
   CASE WHEN t2.ord_idx IS NULL THEN CAST(t1.ord_idx AS CHAR)
   ELSE CONCAT(CAST(t2.ord_idx AS CHAR),'-',CAST(t1.ord_idx AS CHAR)) END