首页 > 解决方案 > 如果他们是我的朋友,MySql 查询来检查 id 列表?

问题描述

所以我有一个使用 sql 命令找到的 ids(userId) 列表,我想用我的朋友表检查他们是否确实是我的朋友,我将提供一个用户 ID,并有一列代表如果他们是,如果他们是我的朋友而不是我的朋友,也将他们分组。

例子:

List of userids:
1
2
3
Friends table:
-------
userId           *the userid sending a friend request*
friendId         *the userid receiving the friend request*
relationshipId   *an unique id for the relationship*
initiated_by     *the userid initiating the friend request*
status           *whether or not the users are friends 'friends' or 'pending'*

示例朋友表数据

我尝试创建一个子查询,首先获取我想要的 id 列表,然后尝试将它与我的朋友表进行比较,但由于朋友表不是双向的,因此无法将其完全放在一起,这意味着每一行代表 2 之间的关系有状态朋友待定的人

标签: mysqlsql

解决方案


使用CASE表达式来获取某人的朋友(即从表中选择 theuserid或 the )。friendidfriends

从 MySQL 8 开始,您可以使用WITH子句来获得可读性:

with friends_of_user_1 as
(
  select case when userid = 1 then friendid else userid end as userid
  from friends
  where 1 in (userid, friendid)
  and status = 'friends'
)
, friends_of_user_2 as
(
  select case when userid = 2 then friendid else userid end as userid
  from friends
  where 2 in (userid, friendid)
  and status = 'friends'
)
select 
  userid,
  userid in (select userid from friends_of_user_2) as is_friend_of_user_2
from friends_of_user_1;

没有相同的WITH

select 
  userid,
  userid in 
  (
    select case when userid = 2 then friendid else userid end as userid
    from friends
    where 2 in (userid, friendid)
    and status = 'friends'
  ) as is_friend_of_user_2
from 
(
  select case when userid = 1 then friendid else userid end as userid
  from friends
  where 1 in (userid, friendid)
  and status = 'friends'
) friends_of_user_1;

推荐阅读