【问题标题】:How do I count the number of comments for each of my posts (MySQL)?我如何计算每个帖子的评论数(MySQL)?
【发布时间】:2021-10-27 12:06:57
【问题描述】:

我在这里有 2 张桌子很重要。一个表称为 POSTS,包含帖子和回复(回复与帖子的处理方式完全相同,但它们在 POSTS.reply 中包含引用帖子的 POSTS.id)。

我的第二个表称为 social 并且包含 POST.id 作为外键,旁边是视图和点赞 + 点赞和查看它的用户。

我使用这个 SELECT 来获取我所有的帖子数据,包括标题、内容...喜欢和视图:

SELECT posts.id, posts.username, posts.time, cat.cat_name, 
posts.title, posts.content, posts.reply,
posts.user_file, posts.audio,
social.views, social.likes
FROM posts
LEFT JOIN user on posts.user_id = user.id 
LEFT JOIN cat ON posts.cat_id = cat.id
LEFT JOIN social ON posts.id = social.post_id
WHERE social.likes IN (SELECT social.likes FROM social 
WHERE social.id IN (SELECT MAX(social.id) 
FROM social GROUP BY post_id))
GROUP BY social.post_id
HAVING posts.reply = 0

我不知道如何让一行包含响应特定帖子的回复数(1 行应该包含我要在页面上显示的所有数据)。

我不知道如何让一行包含响应特定帖子的回复数(1 行应该包含我要在页面上显示的所有数据)。

通常我会得到这样的 cmets,但我不知道如何合并它们:)

SELECT * FROM posts WHERE posts.reply != 0

结构如下:

从我希望收到的查询中:

    "username"  "time"  "cat_name"  "title" "content"   "reply" "user_file" "audio" "views" "likes" "id"    "username"  
   "xxx_user_xxx" "YYYY-MM-DD"  "topic" "Title."    "NSJNASNJSAN?"  "reply: 1/not reply: 0" "/user_uploads/xxx.yyy" "audio or video"    "number of views"   "number oflikes"

现在我想获得一个额外的列 REPLIES(这样做 SELECT * FROM posts WHERE posts.reply != 0)并获取每个帖子的回复数。

【问题讨论】:

  • 请提供包含少量样本数据和预期输出的表结构。
  • 也许这会清除一点。
  • 如果两个表很重要,为什么示例代码引用了五个或六个表?

标签: mysql sql


【解决方案1】:

据我了解,您需要每个帖子的回复。 我用 post_id、user_id 和 reply_id 创建了一个表,并插入了一些虚拟值。

create table t1
(id int, user_id int,reply int);
 
 insert into t1 values(100,1,0);
 insert into t1 values(101,2,100);
 insert into t1 values(102,1,100);
 insert into t1 values(103,2,0);
 insert into t1 values(104,3,103);

然后一个简单的自我加入将使用以下代码为您生成对每个帖子的回复。

select a.id,a.user_id,count(b.reply)
from t1 a
left join t1 b
on a.id=b.reply
group by 1,2;

【讨论】:

  • 这太完美了!澄清一下:我最终将它包含在原始选择 ... LEFT JOIN ( SELECT a.id, count(b.reply) AS b FROM posts a LEFT JOIN posts b on a.id = b.reply GROUP BY a.id, a.user_id HAVING b != 0 ) t2 ON t1.id = t2.id ... 的其他 JOINS 下(HAVING b!= 0 是因为这些是正常帖子而不是回复)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2012-05-02
  • 2017-07-07
  • 1970-01-01
相关资源
最近更新 更多