简体   繁体   English

选择MAX(ID)mysql

[英]Select MAX(ID) mysql

I want to group mysql record with idorig and select the max id in order to select latest record. 我想用idorig分组mysql记录并选择最大id以选择最新记录。

My database content is like that: 我的数据库内容是这样的:

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

My SQL request is: 我的SQL请求是:

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

The sql returns the good id: 102 sql返回好​​的id: 102

But problem is that if I try to return status I got 2 not 0 但问题是,如果我尝试返回状态,我得到2而不是0

How can I change sql request to get the latest id with group idorig and even get the records of 102 not 100 如何更改sql请求以获取组idorig的最新ID,甚至获取102而不是100的记录

The error takes place bacause MySQL doesn't know which status from grouped records should results you. 错误发生,因为MySQL不知道分组记录中的哪个状态会导致您。 It knows that you want max(id) from group but according status is not obvious. 它知道你想从组中获取max(id),但根据状态不明显。 Some SQL engines would tigger exception but not MySQL. 一些SQL引擎会触发异常而不是MySQL。 It returns first record from group (status=2 in this case), I guess. 我猜它会从组返回第一条记录(在这种情况下状态= 2)。 You can do it this way 你可以这样做

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

MySQL is going to get Max(id) for each group (which is unique) then use it in parent query to select interesting data from this particulars records. MySQL将为每个组获取Max(id)(这是唯一的),然后在父查询中使用它从这些详细记录中选择有趣的数据。

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);
SELECT id,message,idorig,status FROM messages where id = (select max(ID) from messages GROUP BY idorig)  order by id desc
Select id, idorig, message, status where id in (SELECT MAX(id) FROM messages GROUP BY idorig)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM