首页 > 解决方案 > 将mysql查询转换为postgres时出错

问题描述

以下查询适用于 MySQL:

SELECT
  f.created_date as time_sec
  ,sum(f.value) as value
  , date_format( f.created_date , '%a') as metric
FROM ck_view_fills as f
GROUP BY date_format(f.created_date, '%a' )

我已将我的数据库迁移到 PostgreSQL,现在我正在将我的查询转换为匹配。我的天真转换如下所示:

SELECT
  f.created_date as time_sec
  ,sum(f.value) as value
  , to_char( f.created_date , "D") as metric
FROM ck_view_fills as f
GROUP BY to_char( f.created_date , "D")

不接受此查询,PostgreSQL 产生的错误消息如下:

查询错误 (7):错误:列“f.created_date”必须出现在 GROUP BY 子句中或用于聚合函数第 2 行:f.created_date as time_sec

据我所知, f.created_date 确实在 group by 子句中使用。我也看到了使用这种语法的例子。那么这个错误的原因是什么,我该如何解决呢?

标签: mysqlsqlpostgresql

解决方案


Postgres 是正确的。事实上,使用最新版本的 MySQL 时,您的查询也会失败——使用默认设置。

只需使用聚合函数:

SELECT MIN(f.created_date) as time_sec,
       SUM(f.value) as value
       TO_CHAR(f.created_date, 'D') as metric
FROM ck_view_fills f
GROUP BY to_char(f.created_date , 'D');

您应该在 MySQL 中使用过类似的构造(关于MIN()-- 或MAX())。


推荐阅读