繁体   English   中英

计算两个MySQL表中发布和第一次评论之间的平均时间

[英]Calculate average time between post and first comment in two MySQL tables

我面对这个(至少对我来说)挑战:

我在那里的帖子都存储在表中的论坛posts和评论表comments 发布后,时间戳记将存储在INT(11) posts.created_at列中。 与注释相同...进行注释时,带有注释的时间戳记存储在comments.created_at

但是,现在我想知道第一条评论显示的平均时间(以秒为单位)。 当然,如果没有给出评论,则不应将其纳入平均值。

这可以在一个SQL查询中完成吗? 如果没有,如何用最少的查询量完成呢?

希望你有一个想法,因为我没有。

如果您使用日期字段作为日期字段,那么类似于:

SELECT AVG(
           DATEDIFF(MIN(comments.created_at), posts.created_at)
          ) 
FROM posts 
INNER JOIN comments on comments.post_primary_key = posts.primary_key

应该得到你需要的东西

但是,正如注释中所指出的那样,您并未将日期存储为日期,请记住尝试:

SELECT AVG(
           MIN(comments.created_at) - posts.created_at
          ) 
FROM posts 
INNER JOIN comments on comments.post_primary_key = posts.primary_key

为了完整性-我的最新建议...您可以尝试以下方法:

SELECT AVG( sub.timeToComment ) 
FROM ( 
       SELECT MIN(comments.created_at) - posts.created_at as timeToComment 
       FROM posts 
       INNER JOIN comments on comments.post_primary_key = posts.primary_key
     ) as sub

但不确定与@Xophmeister方法有何不同

select   posts.id,
         avg(comments.created_at - posts.created_at)
from     posts
join     comments
on       comments.id = posts.id
group by posts.id;

这假设MySQL将正确处理日期时间算法。

编辑正如@MattFellows指出的那样,这个查询是不正确的,因为它通过邮寄分组; 无论我是否使用min(comments.created_at) ,都不要。 实际上,它将返回的结果是完全多余的:对于min ,它将是每个帖子与其第一个评论之间的时间; 没有min ,这是帖子和所有评论之间的平均时间(这是一个相当虚假的指标!)...我垂头丧气:P

正确的查询是:

select avg(min(comments.created_at) - posts.created_at)
from   posts
join   comments
on     comments.id = posts.id;

虽然,这也是时间戳是数字的地方,而不是日期时间,显然,MySQL没有重载运算符。

希望这对你有用:

select   avg(first_comments.first_time - posts.created_at)
from     posts
join    (select   comments.post_id
                  min(comments.created_at) as first_time
         from     comments
         group by post_id) as first_comments
on       first_comments.post_id = posts.id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM