Jump to content

Archived

This topic is now archived and is closed to further replies.

Kris

**SOLVED** GROUP BY in the order they are defined in WHERE?

Recommended Posts

Say I have the following query:
[!--sql--][div class=\'sqltop\']SQL[/div][div class=\'sqlmain\'][!--sql1--][span style=\'color:blue;font-weight:bold\']SELECT[/span] * [color=green]FROM[/color] [color=orange]`table`[/color] [color=green]WHERE[/color] `field`[color=orange]=[/color][color=red]"c"[/color] [color=blue]OR[/color] `field`[color=orange]=[/color][color=red]"d"[/color] [color=blue]OR[/color] `field`[color=orange]=[/color][color=red]"a"[/color] GROUP BY `field` [!--sql2--][/div][!--sql3--]
This returns a result set ordered a, c, d. Is is possible to have the result set ordered by how they were defined in the WHERE part: c, d, a? I tried searching the MySQL manual, but as always, I just can't find what I'm looking for in that excuse for a manual...

Any help is greatly appreciated.

Share this post


Link to post
Share on other sites
It's not exactly a "documented" use of the FIELD() function, but it should work (UNTESTED):

[code]SELECT * FROM `table` WHERE `field`="c" OR `field`="d" OR `field`="a" GROUP BY `field` ORDER BY FIELD(`field`,'c','d','a')[/code]

Hope that helps.

Share this post


Link to post
Share on other sites
[!--quoteo(post=344220:date=Feb 9 2006, 09:07 PM:name=fenway)--][div class=\'quotetop\']QUOTE(fenway @ Feb 9 2006, 09:07 PM) [snapback]344220[/snapback][/div][div class=\'quotemain\'][!--quotec--]
It's not exactly a "documented" use of the FIELD() function, but it should work (UNTESTED):

[code]SELECT * FROM `table` WHERE `field`="c" OR `field`="d" OR `field`="a" GROUP BY `field` ORDER BY FIELD(`field`,'c','d','a')[/code]

Hope that helps.
[/quote]
Spot on, works a charm! Thank you ever so much :)

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.