mysql复杂选择查询从第三个表过滤

wh6knrhe  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(317)

我有三张table。 users, friends and communityusers table。
我正在尝试建立一个类似facebook的群组系统。用户将尝试从朋友列表中搜索他/她的朋友以将他们添加到组中。
所以在这里我试图删除那些已经加入群中的朋友。下面是组用户表 communityusers ..
这是我的结构 communityusers table。

id | community_id | user_id

我无法将此表用于当前查询。

SELECT f.id, u.id as user_id, u.userName, u.firstName, u.lastName, u.profilePic from friends f, users u

WHERE CASE 
WHEN f.following_id=1
THEN f.follower_id = u.id 
WHEN f.follower_id=1
THEN f.following_id = u.id
END 
AND
f.status= 2
AND 
  (
     u.firstName LIKE 's%' OR u.lastName LIKE 's%'
  )

此查询返回用户id的好友列表 1 现在我想从 communityusers table。 user_id 来自此查询的不应出现在 communityusers table。我怎样才能从 communityusers 还是第三桌?
如果问题不清楚,请告诉我。
任何建议,想法和帮助将不胜感激。非常感谢。
编辑
运行查询后,我得到

我的 communityusers

看到了吗 user_id = 2 也可从上述查询中选择。我想移除 user_id = 2 因为它存在于 communityusers table。
我试图创造一个小提琴,但出于某种原因,它不适合我。
再次感谢你。

8i9zcol2

8i9zcol21#

@sadek简单地使用not in,in where条件

SELECT f.id, u.id as user_id, u.userName, u.firstName, u.lastName, u.profilePic
from friends f inner join users u on
CASE WHEN f.following_id=1 THEN f.follower_id = u.id WHEN f.follower_id=1 THEN f.following_id = u.id
END AND f.status= 2
where u.id not in (select distinct user_id from communityusers) and (u.firstName LIKE 's%' OR u.lastName LIKE 's%')
8yparm6h

8yparm6h2#

在给定条件cu.user\u id为null的情况下,尝试对communityuser表使用left join-这将为您提供那些不在communityuser表中的用户

select a.* from 
(SELECT f.id, u.id as user_id, u.userName, u.firstName, u.lastName, u.profilePic from friends f inner join users u
on CASE WHEN f.following_id=1 THEN f.follower_id = u.id WHEN f.follower_id=1 THEN f.following_id = u.id
END AND f.status= 2 where u.firstName LIKE 's%' OR u.lastName LIKE 's%')a
left join (select * from communityuser where community_id<>4) cu on a.user_id=cu.user_id
where cu.user_id is null

相关问题