MySQL GROUP BY query question
I have a table that contains a name of a color (teal, for example) and the associated primary color (blue). Sometimes a color entry can be the same as its associated primary color (red, red).
How can I do a GROUP BY PRIMARY_COLOR where the COLOR for each group are in alphabetical order...except when a COLOR and PRIMARY_COLOR match -- this entry needs to be at the top of the grouping.
Example:
COLOR PRIMARY_COLOR
------------------------
teal blue
magma red
sky blue
red red
magenta red
should res开发者_Go百科ult...
COLOR PRIMARY_COLOR
------------------------
sky blue
teal blue
red red
magenta red
magma red
Order by (ASSOCIATEDCOLOR = COLOR), ASSOCIATEDCOLOR
ORDER BY CASE WHEN COLOR=PRIMARY_COLOR THEN 0 ELSE 1 END, PRIMARY_COLOR
SELECT color, primary_color
FROM colors
ORDER BY
primary_color,
color LIKE primary_color DESC,
color
精彩评论