MySQL 如何选择表中具有最大 ID 的整行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7604893/
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
How do I select an entire row which has the largest ID in the table?
提问by Victor Kmita
How would I do something like this?
我将如何做这样的事情?
SQL SELECT row FROM table WHERE id=max(id)
回答by unutbu
You could use a subselect:
您可以使用子选择:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
Note that if the value of max(id)
is not unique, multiple rows are returned.
请注意,如果 的值max(id)
不唯一,则返回多行。
If you only want one such row, use @MichaelMior's answer,
如果您只想要这样的一行,请使用@MichaelMior 的回答,
SELECT row from table ORDER BY id DESC LIMIT 1
回答by Michael Mior
You could also do
你也可以这样做
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id
is unique among all rows. Otherwise there could be multiple rows with the maximum value for id
and you'll only get one.
这将按其 ID 按降序对行进行排序并返回第一行。这与返回具有最大 ID 的行相同。这当然假设它id
在所有行中都是唯一的。否则可能会有多行的最大值为,id
而您只会得到一行。
回答by Russell Shingleton
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
回答by CakeLikeBoss
You can not give order by
because order by
does a "full scan" on a table.
你不能给,order by
因为order by
对桌子进行“全面扫描”。
The following query is better:
以下查询更好:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
回答by Wella
Try with this
试试这个
SELECT top 1 id, Col2, row_number() over (order by id desc) FROM Table
回答by sumit kumar
One can always go for analytical functions as well which will give you more control
人们也可以随时使用分析功能,这会给您更多的控制
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.
如果您根据数据类型遇到 rank() 函数的问题,那么您也可以从 row_number() 或 density_rank() 中进行选择。