我有用户表和 user_followings 表。表格的基本结构如下:
users: id, name, email
users_followings: following_user_id, follower_user_id
follower_user_id是关注其他人的人。
following_user_id是被其他人跟踪的人 人
我希望可以点击特定用户查看所有信息,例如谁跟随他/她以及他/她正在跟随的人。
SELECT
users.id,
users.name,
users.email
from users
JOIN user_followings ON
user_followings.follower_user_id = users.id
WHERE user_followings.following_user_id = 1
此查询基本上连接两个表并获取所需的结果。
现在假设一个名为“A”的用户已登录,他正在查看用户X的个人资料。有许多人关注了用户X.
让我们说John,Mike,Rusev,Jack等
如何编写一个查询,告诉用户'A'是否跟随John,Mike,Rusev,Jack等跟随上面的查询。
因此,用户A应该能够知道他是否关注John,Mike,Rusev,Jack等
答案 0 :(得分:0)
我的理解是OP希望看到用户跟随当前用户(A)的用户A正在查看(X)
在我的例子中,A是id = 1,X是id = 6
SELECT fu.id, fu.name, fu.email
FROM users u
JOIN users_followings f ON f.userId = u.id
JOIN users fu on fu.id = f.follower
WHERE f.userId = 1
AND f.follower IN (SELECT follower
FROM users_followings
WHERE userId = 6)
我将follower_user_id更改为关注者,将following_user_id更改为userId以免混淆自己
答案 1 :(得分:0)
假设id = 1的用户正在查看id = 2的用户的详细信息,并且您希望id = 1的用户知道id = 2的用户的以下或关注者是否与具有id的用户相关以任何方式= 1。试试这个:
SELECT C.*,
(SELECT 1 FROM user_followings D WHERE D.following_user_id=1 AND
C.id=D.follower_user_id LIMIT 1) flwx_viewing_user,
(SELECT 1 FROM user_followings E WHERE E.follower_user_id=1 AND
C.id=E.following_user_id LIMIT 1) viewing_user_flwx
FROM
(SELECT A.id, A.name, A.email, 'following' relation
FROM users
WHERE EXIST (SELECT 1
FROM user_followings B
WHERE B.following_user_id=2)
UNION ALL
SELECT A.id, A.name, A.email, 'followers' relation
FROM users
WHERE EXIST (SELECT 1
FROM user_followings B
WHERE B.follower_user_id=2)) C;
答案 2 :(得分:0)
我不确定我是否正确但是A的ID = 1而X的ID = 5。 如果后面跟着A
,则此查询将为每个跟在X后面的用户返回信息SELECT
*,
CASE WHEN exists(
SELECT *
FROM following AFOLLOW
WHERE AFOLLOW.follower_user_id = 1
AND XFOLLOWED.follower_user_id = AFOLLOW.following_user_id)
THEN 'FOLLOWING'
ELSE 'NOTFOLLOWING' END
FROM following XFOLLOWED
WHERE following_user_id = 5
AND follower_user_id <> 1;