我有这个查询(在MySQL中运行正常):
SELECT units.*, activity_logs.created_at
FROM "units" left join activity_logs on units.id=activity_logs.unit_id
GROUP BY units.id
ORDER BY activity_logs.created_at desc
Postgres给出了这个错误:
PG::Error: ERROR: column "activity_logs.created_at" must appear in the GROUP BY clause or be used in an aggregate function
我知道Postgres在SQL方面是正确的,但我如何得到我想要的东西?这是与所有单位表连接的每个单位的最新activity_log条目?
提前致谢!
答案 0 :(得分:3)
错误解释了:你需要使用聚合函数来确定这一点,例如:
SELECT units.*, max(activity_logs.created_at)
FROM "units" left join activity_logs on units.id=activity_logs.unit_id
GROUP BY units.id
ORDER BY max(activity_logs.created_at) desc;