我有一个朋友脚本,我在列表上显示朋友,但我想按他们的last active
订购。我有这个代码
SELECT user_one, user_two FROM frnds WHERE user_one='$my_id' OR user_two='$my_id'
表格
|id|user_one|user_two| | 1| 1| 19| | 2| 4| 1| | 3| 9| 403|`
lastactive
位于users
表格中。
谢谢! :)
答案 0 :(得分:0)
你在找这样的东西吗?
SELECT u.name friend_name, u.lastactive
FROM
(
SELECT IF(user_one = ?, user_two, user_one) friend
FROM frnds
WHERE ? IN(user_one, user_two)
) f JOIN users u
ON f.friend = u.id
ORDER BY u.lastactive DESC;
或
SELECT u.name friend_name, u.lastactive
FROM
(
SELECT user_one friend
FROM frnds
WHERE user_two = ?
UNION ALL
SELECT user_two
FROM frnds
WHERE user_one = ?
) f JOIN users u
ON f.friend = u.id
ORDER BY u.lastactive DESC;
注意:在两个查询?
中都是$my_id
的占位符
样本输出(在两种情况下):
| FRIEND_NAME | LASTACTIVE | |-------------|---------------------------------| | User 19 | March, 03 2014 20:30:57+0000 | | User 4 | February, 24 2014 20:30:57+0000 |
这是 SQLFiddle 演示