id username
| 1 | john
| 2 | mike
| 3 | Tim
| 4 | Jake
| 5 | Sam
follower_id followed_id
| 1 | 3
| 1 | 4
post_id author_id
| 1 | 5
| 2 | 4
| 3 | 5
约翰正在追踪蒂姆和杰克。我该如何返回John 不是 关注的帖子列表?
答案 0 :(得分:0)
您可以使用not in
运算符:
SELECT *
FROM posts
WHERE author_id NOT IN (SELECT f.followed_id
FROM followers f
JOIN users u ON f.follower_id = u.id
WHERE username = 'John')
答案 1 :(得分:0)
我们假设表名称为user
,user_to_follower
和post
。
post
表开始,并对用户表进行 INNER JOIN 。user_to_follower
表进行 LEFT JOIN 。由于您想考虑所有未跟随“ John”的用户,并且撰写了帖子 f.follower_id = 1
子句中的ON
设置。is null
所在的用户。尝试以下查询:
SELECT u.id, u.username, p.id AS post_id
FROM post AS p
INNER JOIN user AS u ON p.author_id = u.id
LEFT JOIN user_to_follower AS f ON f.followed_id = u.id
AND f.follower_id = 1
WHERE f.follower_id IS NULL
答案 2 :(得分:0)
一种方法是使用not exists
:
select * from posts
where not exists (
select 1 from followers
where
followers.follower_id = 1
and
followers.followed_id = posts.author_id
)