我有3个表:用户,社区&讯息。
我想检索Joe不关注(id_user=1)
用户
id_user | name
1 Joe
2 Doe
3 Moe
4 Roe
5 Clin
社区
id_follower | id_followed
1 3
1 5
帖子
id_post | id_user | post
24 4 hi
25 5 hello
26 1 how are you
27 3 come on
28 4 let go
29 2 get out
我期待检索的是
24 4 hi - by Roe
28 4 let go - by Roe
29 2 get out - by Doe
我试过这个但没有工作
SELECT p*
FROM community as c
LEFT JOIN users as u ON u.id_user=c.id_followed
LEFT JOIN posts as p ON p.id_user!=c.id_followed
WHERE c.id_follower=1 AND u.id_user!=1
答案 0 :(得分:1)
这应该有效:
select * from Posts
where id_user not in
(select id_followed from Community where id_follower = 1)
答案 1 :(得分:1)
没有必要给出答案,让我们逐步完成逻辑。还有其他方法可以做到这一点,但是因为你问左连接我会做左连接。从帖子开始......
from posts p
然后让我们加入社区
left join community c on c.id_followed = p.id_user and ID_follower = 1
现在,这将为您提供所有帖子的列表以及社区id_followed记录...如果来自社区的记录为空,则来自用户joe的记录不会跟随。因为我们只想要记录乔不遵循
where c.id_followed is null
我们将为用户添加联接以获取海报名称并将其全部放在一起
from posts p
left join community c on c.id_followed = p.id_user and ID_follower = 1
left join users u on u.id_user = p.id_user
where c.id_followed is null
最后将选择行放在一起以获取所需的字段,使用concat获取您想要的名称格式
select p.id_post, p.id_user, concat(p.post , ' by ', u.name)
把它放在一起运行!
答案 2 :(得分:0)
您可以在不在
中使用内部联接select p.*
from Posts p
inner join (
select id_user form community
where id_user not in (
select id_followed
from community
where id_follower =1
)
) t on p.id_user = t.id_user and p.id_user <>1