mysql - 如果他们是我的朋友,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 之间的关系有状态朋友或待定的人
解决方案
使用CASE
表达式来获取某人的朋友(即从表中选择 theuserid
或 the )。friendid
friends
从 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;
推荐阅读
- laravel - 我将如何使用 foreach 接近/修复营业时间
- r - 如何在不影响绘图大小的情况下删除 ggplot 中的刻度标签?
- xamarin - Xamarin.Forms v3.5 应用程序在发布模式下抛出异常
- jenkins - Groovy 闭包 - 缺少属性
- reactjs - React Route 不适用于嵌套 URL
- reverse-geocoding - Google 反向地理编码 - 如何在 street_address 或 route 之间进行选择?
- java - 如何替换数组列表中的重复元素?
- excel - .Find 函数在搜索范围内的最大值时返回错误的问题
- javascript - 无法使用 fetch-mock 模拟 node-fetch
- kubernetes - 基于 Kubernetes 的商店中人员角色的官方命名法?