我正在使用select field1, max(updated_date) from mytable
我得到了max(updated_date)
的正确值,即最大的日期
但是对于field1
,我只得到第一条记录的值,即当我真正想要第三条记录(具有最大日期值的记录)的“ta3”值时,“ta1”。
e.g。
+------------+---------------------+
| field1 | update_date |
+------------+---------------------+
| ta1 | 2012-03-11 11:05:15 |
| ta2 | 2012-03-11 11:05:32 |
| ta3 | 2012-03-11 11:05:56 |
+------------+---------------------+
3 rows in set (0.00 sec)
+------------+---------------------+
| field1 | max(update_date) |
+------------+---------------------+
| ta1 | 2012-03-11 11:05:56 |
+------------+---------------------+
1 row in set (0.00 sec)
答案 0 :(得分:5)
您需要GROUP BY子句或更复杂的查询。
SELECT field1, MAX(updated_date)
FROM mytable
GROUP BY field1
对于样本数据,这将返回3行。
更有可能,你想要:
SELECT t1.field1, t3.max_date
FROM mytable AS t1
JOIN (SELECT MAX(t2.updated_date) AS max_date
FROM mytable AS t2
) AS t3
ON t1.updated_date = t3.max_date;
对于样本数据,这将返回1行:
ta3 2012-03-11 11:05:56
在主要DBMS中,只有MySQL允许您在select-list中混合使用聚合和非聚合列时省略GROUP BY子句。 SQL标准需要GROUP BY子句,您必须列出其中的所有非聚合列。有时,在MySQL中,省略GROUP BY子句会产生您想要的答案;但是,它经常会给出意想不到的答案。
答案 1 :(得分:3)
使用ORDER BY和LIMIT 然后就这么简单:
SELECT field1, updated_date
FROM mytable
ORDER BY updated_date DESC
LIMIT 1;
如果需要大量查询,您可以尝试以下方法:
SELECT t1.field1, t1.updated_date
FROM mytable t1
LEFT JOIN mytable t2
AND t2.updated_date > t1.updated_date
WHERE t2.field1 IS NULL;
简短说明:
对于每一行,请为我提供更新的updated_date
行
但是(WHERE子句)只占用最近updated_date
的行
该技术有时被称为自我排除连接
这是中间结果(没有WHERE子句,并将t2.*
添加到SELECT列表中):
ta1 2012-03-11 11:05:15 ta2 2012-03-11 11:05:32 ta1 2012-03-11 11:05:15 ta3 2012-03-11 11:05:56 ta2 2012-03-11 11:05:32 ta3 2012-03-11 11:05:56 ta3 2012-03-11 11:05:56 null null