数据库关系
我试图显示某个类别中的所有板,但我在 SQL 查询方面遇到问题。我希望它遍历某个类别中的所有帖子,从中获取用户 ID,从用户表中找到用户名,然后计算帖子中有多少评论。
这是表格和一些字段:
boards
board_id
comments - the replies to the post
comment_id
discussion - the posts
discussion_id
discussion_user
discussion_board
discussion_time
discussion_title
users
id
username
最初我有这个:
SELECT
a.discussion_id,
a.discussion_time,
a.discussion_title,
a.discussion_type,
a.discussion_media,
b.username,
Count(c.comment_id) AS totalComments
FROM
discussion a,
users b,
comments c
WHERE
discussion_board='".$board['board_id']."' AND
b.id=a.discussion_user AND
c.comment_post=a.discussion_id
但它只显示帖子,如果它可以找到评论。
我该如何解决这个问题?我仍在学习更多有关 SQL 和数据库关系的知识。左连接?
I'm trying to display all the boards in a certain category, but I'm having trouble with the SQL query. I want it to go through all the posts in a certain category, take in the user id from that, find the username from the users table, and then count how many comments there are in the post.
Here's the tables and some of the fields:
boards
board_id
comments - the replies to the post
comment_id
discussion - the posts
discussion_id
discussion_user
discussion_board
discussion_time
discussion_title
users
id
username
Originally I had this:
SELECT
a.discussion_id,
a.discussion_time,
a.discussion_title,
a.discussion_type,
a.discussion_media,
b.username,
Count(c.comment_id) AS totalComments
FROM
discussion a,
users b,
comments c
WHERE
discussion_board='".$board['board_id']."' AND
b.id=a.discussion_user AND
c.comment_post=a.discussion_id
But it only shows post if it can find comments.
How can I fix this? I'm still learning more about SQL and database relationships. Left joins?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
左连接是正确的选择,因为它们将从 a 中提取所有内容,无论 b 或 c 中是否有相应的条目。有关连接(以及一般的 SQL)的更多信息可以在此处找到。
Left joins are the way to go, since they will pull everything from a, regardless of whether there's a corresponding entry in b or c. More on Joins (and SQL in general) can be found here.
使用 SQL-92 连接语法(显式使用
join
)关键字进行连接,它使查询更具可读性,尤其是在开始添加外连接之后。是的,您需要一个
左连接
到您的评论表。Use SQL-92 join syntax (where you explicitly use the
join
) keyword to join, it makes the query more readable, especially after you start adding outer joins.And yes, you want a
left join
to your comments table.