mysql - 从用户,帖子和评论表中获取评论计数和用户的所有帖子

时间:2016-11-22 08:23:33

标签: mysql

我有3个用户,帖子和评论表。用户表字段是

ID,姓名,性别,电话

帖子表格字段是

post_id,user_id,帖子,时间

评论表字段是

id,user_id,comment,post_id,time

我想获得这些领域的价值

姓名,性别,职位,时间,计数(评论)

2 个答案:

答案 0 :(得分:2)

es

答案 1 :(得分:1)

试试这个:

如果comments.id为null,则此处将替换

SELECT User.name, User.gender, posts.posts, count(distinct ifnull(comments.id, 0)) as commentcount
FROM User
JOIN posts on user.id = posts.user_id
JOIN comments on user.id =comments.user_id
GROUP User.name, posts.posts

如果您想使用性别分组,请将User.gender添加到分组依据。

相关问题