Jump to content

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


zq29

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.
Link to comment
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.
Link to comment
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 :)
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.