简体   繁体   English

MySQL选择两列之一匹配的位置,并从另一张表中按列排序

[英]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 tableuser1user2 ,因此当我不知道哪一列包含该朋友时,我真的不知道如何加入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.

相关问题 SELECT 来自两个表 WHERE 每个表中的不同列等于 $id ORDER BY 公共列(PHP / MySQL) - SELECT from two tables WHERE different columns in each table equal $id ORDER BY common column (PHP/MySQL) 将值从一个表中的列复制到另一个表中的列,其中另一个值与MySQL匹配 - Copy the values from a column in one table to a column in another table where another value matches MySQL mysql-表的两列和另一列的计数 - mysql - count of two columns of a table and one column from another MYSQL:从表中选择与列中的字符串匹配的地方? - MYSQL: select from table where a string in a column matches? 从两个表中选择多个列,其中一个表的一列具有多个where条件,并将它们按两列分组并按顺序排序 - Selecting multiple columns from two tables in which one column of a table has multiple where conditions and group them by two columns and order by one 连接一个表中的两列,并查找它在另一个表中没有出现的位置 mysql - Concatenate two columns from one table and look for where it does not show up in another table mysql MySQL查询汇总表中的一列,其中两个列组合在一起时是唯一的 - Mysql query to sum a column from a table where another two columns are unique when combined together 插入到多个列的select中,其中只有一列来自另一个表 - insert into select for multiple columns, where only one column is from another table 从一个表中选择并按另一表的列排序 - Select from one table and order by column of another table MYSQL仅在该表的列值与另一表的列值匹配的情况下,才如何从该表中选择数据? - MYSQL How do I select data from one table only where column values from that table match the column values of another table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM