开发者

Query table, but get a specific id listed first

开发者 https://www.devze.com 2023-03-17 06:47 出处:网络
I have a table in my database, named \"folders\". How do I make a q开发者_Go百科uery that output everything but always list a specific ID first?

I have a table in my database, named "folders".

How do I make a q开发者_Go百科uery that output everything but always list a specific ID first?

Lets use ID "12345" for the folder I want to be listed first.

I currently use this:

mysql_query("SELECT id, name FROM folders WHERE memberid='$session_userid' ORDER BY name ASC ") or die(mysql_error());

I tried to Google it, but nothing comes up and I'm totally blank :(


You just need to add another ORDER BY clause for your special criteria. Any expression that will give one value for your "preferred" record and a second value for all the other records will work.

mysql_query("SELECT id, name FROM folders
    WHERE memberid='$session_userid'
    ORDER BY IF(id=12345, 1, 2), name ASC") or die(mysql_error());


ORDER BY FIELD() allows to sort rows by custom values, so this should work:

SELECT id, name 
FROM folders 
WHERE memberid='$session_userid' 
ORDER BY FIELD( id, '12345' ) DESC , name ASC

If you need 2 folders to be listed first (let's say id1='12345' and id2='23456') the query would be

SELECT id, name 
FROM folders 
WHERE memberid='$session_userid' 
ORDER BY FIELD( id, '12345' , '23456' ) DESC , name ASC

EDITTED: Added "DESC" to the ORDER BY FIELD(). ASC being the default, the folder with id="12345" would be listed last!

0

精彩评论

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