从下表中,如何为每个 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/