选择MAX(ID)mysql

时间:2014-09-23 12:43:36

标签: mysql group-by

我想用idorig对mysql记录进行分组,并选择最大ID以选择最新记录。

我的数据库内容如下:

ID     | IDORIG     | MESSAGE    | STATUS
100    | 100        | azerty     | 2
101    | 100        | azerty     | 1
102    | 100        | azerty     | 1
103    | 100        | azerty     | 0
104    | 104        | azerty     | 0
105    | 104        | azerty     | 0
106    | 104        | azerty     | 0
107    | 104        | azerty     | 0
108    | 104        | azerty     | 0

我的SQL请求是:

SELECT MAX(id),message,idorig,status FROM messages GROUP BY idorig order by id desc

sql返回好​​的id: 102

但问题是,如果我尝试返回状态,我会 2 而不是 0

如何更改sql请求以获取group idorig的最新ID,甚至获取102而不是100的记录

4 个答案:

答案 0 :(得分:14)

错误发生,因为MySQL并不知道分组记录中的哪个状态会导致您。它知道你想从组中获取max(id),但根据状态不明显。一些SQL引擎会触发异常而不是MySQL。我猜它会从组返回第一条记录(在这种情况下状态= 2)。你可以这样做

Select id, idorig, message, status where id in (SELECT MAX(id) FROM messages GROUP BY idorig)

MySQL将为每个组获取Max(id)(这是唯一的),然后在父查询中使用它从这些详细记录中选择有趣的数据。

答案 1 :(得分:4)

select ID,idorig,Message,Status from messages order by ID desc limit 1;

Select ID,idorig,Message,Status from messages where ID = (select max(ID) from messages);

答案 2 :(得分:-2)

SELECT id,message,idorig,status FROM messages where id = (select max(ID) from messages GROUP BY idorig)  order by id desc

答案 3 :(得分:-3)

Select id, idorig, message, status where id in (SELECT MAX(id) FROM messages GROUP BY idorig)