如何在 MySQL 中同时使用 MAX 和 LIMIT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1150715/
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:42:11  来源:igfitidea点击:

How can I use MAX and LIMIT together in MySQL

mysqllimitmax

提问by kersjous

I have a table with the following structure:

我有一个具有以下结构的表:

ID | Color

身 | 颜色

1 | red
2 | blue
3 | yellow
8 | purple
10| green
.
.
.
100|yellow

1 | 红色
2 | 蓝色
3 | 黄色
8 | 紫色
10| 绿色

.
.
100|黄色

I would like to be able to grab the MAX ID value for the first 5 rows.

我希望能够获取前 5 行的 MAX ID 值。

For example, I would like to do something like so: Select MAX(ID) From Table LIMIT 5

例如,我想做这样的事情: Select MAX(ID) From Table LIMIT 5

Hoping this would return the value 10

希望这将返回值 10

But, MySQL keeps returning 100...its like MySQL does not even see the LIMIT clause.

但是,MySQL 不断返回 100 ......就像 MySQL 甚至没有看到 LIMIT 子句。

回答by gahooa

It sounds like you want to select the top 5 records (ordered by ID) and then get the highest value of that group? If so:

听起来您想选择前 5 条记录(按 ID 排序),然后获取该组的最高值?如果是这样的话:

SELECT
    MAX(ID)
FROM
    ( 
         SELECT ID 
         FROM YourTable
         ORDER BY ID
         LIMIT 5
    ) as T1 

回答by kersjous

There is better way to do this than subselect:

有比子选择更好的方法来做到这一点:

SELECT id FROM table LIMIT 4,1

Get one row but skip 4 first.. Add 'order by id' if this is MyISAM table.

获取一行但先跳过 4.. 如果这是 MyISAM 表,则添加“按 ID 排序”。

回答by lucasmo

Use a subselect:

使用子选择:

SELECT MAX(id) FROM (SELECT id FROM table LIMIT 5);

That might not quite be valid SQL, but that should give you a general idea.

这可能不是有效的 SQL,但这应该给你一个大致的概念。

回答by volgot

If you have a table with the following structure

如果您有一个具有以下结构的表

ID | Color

1 | red
2 | blue
3 | yellow
8 | purple
10| green
.
.
.
100|yellow

The MAX ID value for the first 5 (AUTO_INCREMENT?) values is 5. Btw, the MAX ID value for the first 6 values is 6. And 100 for all values. Best regards.

前 5 个 (AUTO_INCREMENT?) 值的 MAX ID 值为 5。顺便说一句,前 6 个值的 MAX ID 值为 6。所有值的 MAX ID 值为 100。此致。