[英]MySQL select where one of two columns matches and order by column from another table
I have the following mysql statement where I select all friends for a user. 我有以下mysql语句,其中我为用户选择了所有朋友。
SELECT *
FROM friends
WHERE (user1 = FRIEND_ID_HERE AND confirmed = 1)
OR (user2 = FRIEND_ID_HERE AND confirmed = 1);
The problem is that the friend can be either user1
or user2
in the friends table
so I dont really know how to join the members table
and sort them by last_online
when I dont know which column contains the friend. 问题是,朋友可以在friends table
为user1
或user2
,因此当我不知道哪一列包含该朋友时,我真的不知道如何加入members table
并按last_online
对它们进行排序。
How can I do this most efficiently? 我怎样才能最有效地做到这一点? Thanks! 谢谢!
table members 表成员
user_id | username | last_online
--------------------------------
1 | user1 | 1502296162
2 | user2 | 1502296161
3 | user3 | 1502296160
4 | user3 | 1502296159
table friends 表朋友
id | user1 | user2 | confirmed
-------------------------------
1 | 1 | 2 | 1502296162
2 | 3 | 1 | 1502296161
3 | 2 | 4 | 1502296160
I think what you need is something like this 我认为您需要的是这样的东西
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;
SELECT * FROM friends WHERE confirmed=1 AND friend_id_here IN (user1,user2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.