开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜