简体   繁体   中英

Query table, but get a specific id listed first

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

How do I make a query 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM