mysql - Order BY 根本不起作用

标签 mysql sql

从下表中,如何为每个 id、head 和 userId 选择最新的记录?这件事让我发疯。

"id"    "head"  "type"  "updated"   "userId"    "addedDate"
"1"     "2"     "0"     "1"         "1"         "2013-11-23 21:09:23"
"1"     "2"     "1"     "1"         "1"         "2013-11-23 21:09:40"
"2"     "2"     "0"     "1"         "1"         "2013-11-23 21:09:44"
"2"     "2"     "1"     "0"         "1"         "2013-11-23 21:09:47"

查询失败 - 都不会返回所需的结果

SELECT id, addedDate FROM test WHERE userId = 1 and head = 2 GROUP BY id HAVING MAX(addedDate);
SELECT id, addedDate FROM test WHERE userId = 1 and head = 2 GROUP BY id ORDER BY MAX(addedDate) DESC ;

当前错误结果

"id"    "addedDate"
"2"     "2013-11-23 21:09:44" // Incorrect. This is the first one for it
"1"     "2013-11-23 21:09:23" // Incorrect. This is the first one for it

期望的结果

"id"    "addedDate"
"2"     "2013-11-23 21:09:47" // The one that was added last
"1"     "2013-11-23 21:09:40" // The one that was added last 

编辑 这里的整个问题是我不想在选择中使用 max() ,因为我正在使用 PDO::FETCH_KEY_PAIR

最佳答案

SELECT id, MAX(added_date) FROM test WHERE userId=1 AND head=2 Group By id

关于mysql - Order BY 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20172842/

相关文章:

php - 排序顺序参数

mysql - 选择 MySQL 中行日期之间的差异

mysql - AWS Aurora 与 MySQL 的兼容性

php - MySQL 查询,GET(id)?!

mysql - 使用mysql将所有博客文章传输到另一个wordpress数据库

mysql从一个表列复制到另一个具有完整性约束的空表

mysql - 如何将带有子查询同表的MySQL select语句转换为update语句?

MYSQL - 在一个查询中使用不同 where 子句的不同计数

mysql - 对多行 SQL 求和

mysql游标需要很长时间才能执行