简体   繁体   English

多对多查询

[英]Many to Many to Many Query

I have the following tables: 我有以下表格:

user (id, name, email) follow (id, follower_id, following_id) post (id, user_id, title, body) 用户(标识,名称,电子邮件)关注(标识,folder_id,following_id)帖子(标识,user_id,标题,正文)

Now follow means I (user_id = 23) follow another user (user_id = 12) and maybe a few more. 现在关注意味着我(user_id = 23)关注另一个用户(user_id = 12),也许还有更多。

I want to make a query where it can display ALL posts made by ALL people I follow. 我想查询一个可以显示我关注的所有人的所有帖子的查询。

Is it possible with a single Query? 单个查询可以吗?

Absolutely, however make sure you have proper indexes otherwise it may take a while! 绝对可以,但是请确保您具有正确的索引,否则可能需要一段时间!

SELECT `user`.`id` AS `user_id`, `user`.`name`, `post`.`id` AS `post_id`, `post`.`title`, `post`.`body`
FROM `follow`
JOIN `user` ON `user`.`id`=`follow`.`following_id`
JOIN `post` ON `post`.`something...` # You're missing an "author" field in your posts table!
WHERE `follow`.`following_id` = 23

You don't mention it in the question, but you gotta have a column such as poster_id that identifies who made the post in your Post table. 您没有在问题中提到它,但是您必须有一列诸如poster_id来标识谁在您的Post表中发布了该帖子。 Having that, you can do: 有了它,您可以执行以下操作:

SELECT p.* 
FROM posts p
INNER JOIN follow f ON p.poster_id = f.following_id
WHERE f.follower_id = 23;

This will give you all the posts from the users followed by user 23. 这将为您提供来自用户的所有帖子,然后是用户23。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM