我正在构建一个应用程序,旨在向用户展示一个随机选择的用户从一个列表,他/她可能喜欢跟随他们不跟随对方已经。
我有2个表,一个表有用户列表,第二个表有2列,显示"following"关系。
表1 user - user_id, instagram_id, join_date
表2 users_follow - instagram_id_1, instagram_id_2我只是想知道是否有人可以指出我在正确的方向上如何创建连接,并选择一个随机行,其中2个用户不跟随对方?我已经尝试过左连接,但没有任何运气到目前为止。
这是目前为止的代码SELECT *
FROM users
INNER JOIN `user_follows` ON users.instagram_id = user_follows.instagram_id
WHERE user_follows.instagram_id != 'insta123'
谢谢你的帮助
我建议您创建一个子查询来获取您的关注者列表。然后使用LEFT JOIN,并通过测试NULL来查找那些不是follower的用户。
SELECT users.* from users
left join
(
SELECT
users_follows.instagram_id_2 as 'instagram_id'
from users
inner join users_follows on users.instagram_id=users_follows.instagram_id_1
where users.instagram_id = 'insta123'
) as followers on users.instagram_id = followers.instagram_id
where followers.instagram_id is null
and users.instagram_id != 'insta123' # you can't follow yourself
我已经用你的结构的复制品测试了它,它工作得很好。