[英]How to properly join these four tables in SQL?
I'm currently creating a small application, where users can subscribe to different channels to see the corresponding posts.我目前正在创建一个小应用程序,用户可以在其中订阅不同的频道以查看相应的帖子。
My database looks like this (simplified):我的数据库看起来像这样(简化):
Now I'm trying to get all the information out of the post table (all columns), for all the posts that are connected to any channel a specific user may have subscribed.现在,我正在尝试从帖子表(所有列)中获取所有信息,这些信息针对与特定用户可能订阅的任何频道相关的所有帖子。
Example: A user (id_user = 0) has subsribed to three channels (id_channel = 1, 2 and 3) and now wants to see all posts in these channels (each post where fk_channel = 1 or 2 or 3).示例:用户 (id_user = 0) 订阅了三个频道(id_channel = 1、2 和 3),现在想要查看这些频道中的所有帖子(每个帖子的 fk_channel = 1 或 2 或 3)。
I tried many variations using different joins, however I couldn't manage to find the correct query.我使用不同的连接尝试了许多变体,但是我无法找到正确的查询。 One of my last attempts looked something like this (which does not work...):
我最后一次尝试看起来像这样(这不起作用......):
SELECT * FROM posts
INNER JOIN channels ON posts.fk_channel = channels.id_channel
INNER JOIN subscriptions ON channels.id_channel = subscriptions.fk_subcribed_channel
INNER JOIN users ON subscriptions.fk_subscibed_by = users.id_user
If you have the user's id then there is no need to join the table users
, because you can use the column fk_subscibed_by
of subscriptions
:如果您有用户的 id,则无需加入表
users
,因为您可以使用subscriptions
fk_subscibed_by
列:
SELECT p.*
FROM subscriptions s
INNER JOIN channels c ON c.id_channel = s.fk_subcribed_channel
INNER JOIN posts p ON p.fk_channel = c.id_channel
WHERE s.fk_subscibed_by = 0
If you want to get all the columns of the joined tables, use SELECT *
instead of SELECT p.*
which returns only the columns from posts
.如果要获取连接表的所有列,请使用
SELECT *
而不是SELECT p.*
,后者仅返回来自posts
的列。
If your rappresentation is right this should work properly:如果您的 rappresentation 是正确的,这应该可以正常工作:
SELECT * FROM posts
LEFT OUTER JOIN channel ON posts.fk_channel = channel.id_channel
LEFT OUTER subscriptions ON channel.id_channel = subscriptions.fk_subcribed_channel
LEFT OUTER users ON subscriptions.fk_subscibed_by = users.id_user
Like this you should be able to get each post from each channel the user is subscribed.像这样,您应该能够从用户订阅的每个频道中获取每个帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.