按时间戳排序工作不正确

时间:2013-11-23 16:05:21

标签: mysql sql

从下表中,我试图通过distinct(id)选择ordertimestamp desc。但我似乎没有得到正确的结果。

"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 distinct(id) as id, addedDate from test 
where userId = 1 group by id order by addedDate desc;

当前结果

"id"    "addedDate"
"2"     "2013-11-23 21:09:44"
"1"     "2013-11-23 21:09:23" // This is wrong. 
                 //It should have been the one with 2013-11-23 21:09:40

期望的结果

"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 

3 个答案:

答案 0 :(得分:1)

您的查询以非常错误的方式使用GROUP BY。您希望为每个addedDate找到最大id

SELECT id, MAX(addedDate) AS max_addedDate 
FROM test 
WHERE userId = 1 
GROUP BY id 
ORDER BY max_addedDate DESC ;

即使您不想在SELECT列表中显示最长日期,您仍然可以在ORDER BY子句中使用它:

SELECT id
FROM test 
WHERE userId = 1 
GROUP BY id 
ORDER BY MAX(addedDate) DESC ;

如果您有不同的要求(正如您在评论中提到的那样)并且您还希望从表中显示更多列(但仍然是针对每个ID具有最大日期的行),则可以将以上查询与联接一起使用:

SELECT t.id, t.addedDate, t.type           -- whatever columns you want from `t`
FROM test AS t
  JOIN
    ( SELECT id, MAX(addedDate) AS addedDate 
      FROM test 
      WHERE userId = 1 
        AND head = 2
      GROUP BY id 
    ) AS m
    ON  m.id = t.id
    AND m.addedDate = t.addedDate
WHERE t.userId = 1 
  AND t.head = 2
ORDER BY t.addedDate DESC ;

答案 1 :(得分:-1)

尝试添加条款:

HAVING MAX(addedDate)

答案 2 :(得分:-1)

尝试这样做:

  

SELECT DISTINCT id FROM test ORDER BY order by convert(datetime,addedDate,103)DESC;

convert()会将日期转换为容易确定的varchar。