0

我有一个 MySQL 表(称为formstatus),它有 4 列:idformstatustimestampid作为主键,formstatus一起唯一。我想获得status具有第二个最近时间戳的行集(特别是)form。我试过

SELECT form, status FROM (
  SELECT form, status, timestamp
  FROM formstatus
  WHERE timestamp < max(timestamp)
  GROUP BY form) as a
WHERE timestamp = max(timestamp)
GROUP BY form

但它不起作用,因为显然在 where 子句中不允许聚合。那么,是否有一个查询可以返回我正在寻找的信息?

4

2 回答 2

3

试试这个查询 -

SELECT
  t1.*, COUNT(*) pos
FROM formstatus t1
  LEFT JOIN formstatus t2
    ON t2.form = t1.form AND t2.timestamp >= t1.timestamp
GROUP BY
  t1.form, t1.timestamp
HAVING
  pos = 2;
于 2012-05-23T15:04:53.230 回答
0

生成错误是因为您不能在WHERE子句中使用聚合。尝试将您的条件移至HAVING子句。

GROUP BY form
HAVING timestamp < max(timestamp)
于 2012-05-23T15:02:51.757 回答