MySQL AVG TIME 给出奇怪的行为

标签 mysql

在 TIME(3) 属性上执行 AVG 时,我遇到了令人困惑的行为。

查询如下:

SELECT
    SEC_TO_TIME(STD(`duration`)) standard_deviation,
    SEC_TO_TIME(AVG(`duration`)) mean,
    MIN(`duration`) min,
    MAX(`duration`) max
FROM `races`

那么结果是:

enter image description here

正如您所见,平均值大于最大值。这怎么可能。我在查询中做错了什么吗?

duration 列是一个 TIME(3) 列。代表比赛的持续时间。

最佳答案

如mysql手册aggregate functions说:

The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the values to numbers, losing everything after the first nonnumeric character.) To work around this problem, convert to numeric units, perform the aggregate operation, and convert back to a temporal value. Examples:

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name;

所以,这就是你需要做的:

SELECT
    SEC_TO_TIME(STD(`duration`)) standard_deviation,
    SEC_TO_TIME(AVG(time_to_sec(`duration`) + (EXTRACT(MICROSECOND from duration) / 1000000))) mean,
    MIN(`duration`) min,
    MAX(`duration`) max
FROM `races`

关于MySQL AVG TIME 给出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244449/

相关文章:

php - 将 MySQL 数据从一个表 move 到另一个表跳过重复(或覆盖)

mysql - 选择数据范围,从第一次出现到最后一次出现

mysql - 备份 MySQL 数据库的安全方法?

php - 填充返回值 MySQL

php - 连接到远程服务器并执行简单的数据库查询时出现问题

php - 一张表中可以添加两个同名字段吗?

MYSQL 查询 - 使用格式但没有逗号

php - 计算用户在搜索结果中的排名[Laravel]

php - sql数据库前缀

PHP MySQL 创建讨论区