选择 MAX(ID) mysql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25995434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:04:38  来源:igfitidea点击:

Select MAX(ID) mysql

mysqlgroup-by

提问by Nathan

I want to group mysql record with idorig and select the max id in order to select latest record.

我想将 mysql 记录与 idorig 分组并选择最大 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 2not 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 的记录

回答by Mateusz Nowak

The error takes place bacause MySQL doesn't know which status from grouped records should results you. It knows that you want max(id) from group but according status is not obvious. Some SQL engines would tigger exception but not MySQL. It returns first record from group (status=2 in this case), I guess. You can do it this way

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

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)(这是唯一的),然后在父查询中使用它来从该特定记录中选择有趣的数据。

回答by Giles

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

or

或者

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

回答by lordkain

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

回答by Pravesh Singh

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