Orden compleja de Mysql por

I have 3 columns in my table

  1. estado enum('Completed','Incomplete','In Progress')
  2. gravedad enum('High','Low','Moderate')
  3. creado datetime

Now currently i am ordering by severity ASC created DESC status DESC. which is not working right. This is how i want it to be listed.

  1. Incomplete - High
  2. Incomplete - moderate
  3. Incomplete - low
  4. In Progress - High
  5. In Progress - moderate
  6. In Progress - low
  7. Completed - High
  8. Completed - moderate
  9. Completed - low

preguntado el 27 de agosto de 11 a las 14:08

What do you end up with? What happens if you put status first then created then severity? -

3 Respuestas

Puedes utilizar una case to order rows like that:

select  *
from    YourTable
order by
        case 
        when status = 'Incomplete' and severity = 'High' then 1
        when status = 'Incomplete' and severity = 'Moderate' then 2
        ...
        end

Respondido 27 ago 11, 18:08

+1: But this question really demonstrates why using a natural key isn't always the best idea. A lookup table using a numeric primary key would make this much simpler & robust if more severity/etc values get added. - Ponis dios mio

+1 This should be able to be simplified to multiple cases shouldn't it? One case for status and one for severity? Would save OP having to write out all permutations. - Dabbler decente

As well as Andomar's solution, I'd consider having proper tables for status and severity. Not enums.

You can imply sort order from the key of these tables, but I'd probably have a "SortOrder" column for future use.Then you can JOIN the tables and order by the SortOrder.

No need repeat the CASE in every query that needs it

Edit: Simplifying Andomar's idea...

order by
    case status
       when 'Incomplete' then 1
       when 'In Progress' then 2
       when 'Completed' then 3
    END,
    case severity
       when 'High' then 1
       when 'Moderate' then 2
       when 'Low' then 3
    END

Respondido 27 ago 11, 19:08

+1 Suggested this to Andomar as well, but I wasn't sure if this actually possible. - Dabbler decente

You can store Status and Severity as numbers, the use:

SELECT ... FROM ... ... ORDER BY STATUS [ASC/DESC], SEVERITY [ASC/DESC]

ASC or DESC will depend on wich numbers you choose.

To have severity and status as text you can use a IF/Switch or a INNER JOIN if you want more Status/Severity

Respondido 27 ago 11, 19:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.