简体   繁体   中英

Mysql PHP query. How do you “order by” two different columns in the database together?

I have 2 columns in my database. One is named "name01" and the other is named "name02". This database displays friends on my app. When I go to my friends list on the app I want all my friends displayed by name in asc order. The problem is users names could be in "name01" or "name02" depending on who sent the friend request first. How would you "order by" both name01 & name02 at the same time? I have tried doing it with a comma (ORDER BY name01, name02) but it orders one first and then the other so the names aren't all in alphabetical order.

 $sql = mysql_query("SELECT * FROM friends WHERE id01 = '$id' AND status01 = '1' OR id02 = '$id' AND status02 = '1' **ORDER BY name01, name02** Limit 500");

Above will order name01 separately from name02.

Use the GREATEST() function and then ordering:

SELECT friends.*, GREATEST(IFNULL(name01, 0), IFNULL(name02, 0)) as greatest_name 
FROM friends 
WHERE id01 = '$id' AND status01 = '1' OR id02 = '$id' AND status02 = '1'
ORDER BY greatest_name Limit 500

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