我有以下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
并按last_online
对其进行排序。我怎样才能最有效地做到这一点?谢谢!
表成员
user_id | username | last_online
--------------------------------
1 | user1 | 1502296162
2 | user2 | 1502296161
3 | user3 | 1502296160
4 | user3 | 1502296159
表朋友
id | user1 | user2 | confirmed
-------------------------------
1 | 1 | 2 | 1502296162
2 | 3 | 1 | 1502296161
3 | 2 | 4 | 1502296160
最佳答案
我认为您需要的是这样的东西
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;
关于mysql - MySQL选择两列之一匹配的位置,并从另一张表中按列排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45595977/