我有以下mysql语句,我为用户选择了所有朋友。
/
问题是,SELECT *
FROM friends
WHERE (user1 = FRIEND_ID_HERE AND confirmed = 1)
OR (user2 = FRIEND_ID_HERE AND confirmed = 1);
中的朋友可以是user1
或user2
,所以我真的不知道如何加入friends table
并按{members table
排序1}}当我不知道哪一列包含朋友时。
我怎样才能最有效地完成这项工作?谢谢!
表格成员
last_online
表朋友
user_id | username | last_online
--------------------------------
1 | user1 | 1502296162
2 | user2 | 1502296161
3 | user3 | 1502296160
4 | user3 | 1502296159
答案 0 :(得分:2)
我认为你需要的是这样的东西
SELECT * FROM members JOIN (
SELECT user2 AS id FROM friends WHERE (user1 = FRIEND_ID_HERE AND confirmed = 1)
UNION
SELECT user1 AS id FROM friends WHERE (user2 = FRIEND_ID_HERE AND confirmed = 1)
) f ON memebers.id = f.id
ORDER BY last_online;
答案 1 :(得分:0)
SELECT * FROM friends WHERE confirmed=1 AND friend_id_here IN (user1,user2)