【发布时间】:2015-04-05 10:48:15
【问题描述】:
我有 4 张桌子:
posts [post_id post_title post_body post_date post_by post_accepted]
users [user_id user_name user_pw]
comments [comment_id comment_user comment_co comment_post comment_date]
categories [categorie_id categorie_name]
每个表都包含一个数据,所有数据都属于表帖子:
categories<-posts
posts<-users
posts<-comments<-users
我想获得 id 为 post_id 的帖子,并获得一个 cmets 和谁发布它并获得类别名称和 id。
我试过了,但我收到了帖子,但不是所有的 cmets,或者如果帖子没有评论,它不会出现。
这是我的 SQL 查询:
SELECT COUNT(comment_id),comments.*,categories.*,users.*,posts.*
FROM posts
JOIN categories on (posts.post_id = categories.categorie_id)
JOIN users on (posts.post_by = users.user_id)
LEFT JOIN comments on (posts.post_id = comments.comment_post)
WHERE posts.post_id='34'
AND posts.post_accepted = '1' ;
【问题讨论】:
-
cmets 必须使用左外连接。内连接将要求表中有行。此外,如果有多个 cmets,您将获得多行,并且 count 将产生 1。您不能像这样在一行中获得多行。
-
还要考虑列的命名。 Post_by 不是指向用户表或使用单独的类别表的好名称,该表只为每个帖子保存一个值。如果始终存在 1-1 关系,则它们属于同一个表。如果表是用户,列应该只是名称,而不是用户名,因为它是什么名称很明显。 post_title、post_body 等也一样。
-
感谢@SamiKuhmonen 我创建函数来获取评论计数并将它们加入数组