MySql:Order by和Group结合不提供最新记录

时间:2012-04-09 07:19:29

标签: php mysql sql

使用以下查询我正在寻找一种解决方案来获取具有某些条件的最新记录。 但它给了我第一个记录,而不是最新记录。我认为它只考虑小组 请告诉我

SELECT * FROM `contacts` WHERE `id_receiver`=1  GROUP BY `id_thread` ORDER BY created DESC

id   id_sender   id_thread sender_email   id_receiver      created(datetime)
1    2             2         51             1                2012-03-24 13:44:48
2    4             4         1              5                 2012-04-26 13:46:05
3    2             2         51             1                2012-04-09 12:12:30

必需的输出

id   id_sender  id_thread sender_email   id_receiver      created(datetime)
3    2           2         51             1                2012-04-09 12:12:30

我做了一个测试,只是交换顺序和分组,给我一个错误。

任何人都可以看看这个?感谢。

编辑编辑问题,忘记写id_thread

2 个答案:

答案 0 :(得分:3)

当您的表格中没有GROUP BY id_thread列时,您如何id_thread

SELECT * 
FROM contacts 
WHERE id_receiver = 1 
                                 --- GROUP BY id_thread
                                 --- removed 
ORDER BY created DESC
LIMIT 1                          --- only show one row

根据您的评论,您想要的是每个created的最新行(按id_thread排序)行,这是一个不同且更复杂的查询。这种查询甚至还有一个标记,名为[greatest-n-per-group]

SELECT c.* 
FROM contacts AS c
  JOIN
    ( SELECT id_thread, MAX(created) AS created 
      FROM contacts 
      WHERE id_receiver = 1  
      GROUP BY id_thread
    ) AS g 
    ON (g.id_thread, g.created) = (c.id_thread, c.created) 
WHERE c.id_receiver = 1  

答案 1 :(得分:0)

如果记录按顺序排序,那么你也可以通过id排序 - 当且仅当它按顺序创建时 -