订单BY根本不起作用

时间:2013-11-24 09:06:24

标签: 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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

要获得所需的结果,只需执行以下操作:

SELECT id, MAX(addedDate) 
  FROM test 
 WHERE userId = 1 
   AND head = 2 
 GROUP BY id 

如果你想要一个添加日期最大的记录,你必须完全包含在你的HAVING子句中:

HAVING addedDate = MAX(addedDate)

但在这种情况下没有必要。

如果您想在一个查询中查询所有最新日期,即userid和head,只需将其设为:

SELECT id, userId, head, MAX(addedDate) 
  FROM test 
 GROUP BY id, userId, head

可选择添加

 ORDER BY 1, 2, 3