简体   繁体   中英

Get the last result from the mysql resultset in mysql stored procedure

I have a table with data as follows.

Name      Age
Alex      23
Tom       24

Now how do i get the last row only ie. the row containing "Tom" in Mysql Stored Procedure using the select statement and without considering the Name and Age. Thanks.

without considering the Name and Age

That's not possible. There's no "first" or "last" row in a result set as long as you don't add an ORDER BY a_column to your query. The result you see is kind of random. You might see the same result over and over again, when you execute the query 1000 times, this might change however when an index gets rewritten or more rows are added to the table and therefore the execution plan for the query changes. It's random!

添加ORDER BY并将limit 1为您select * from...

SELECT TOP 1 name, age FROM table ORDER BY name desc or use ORDER BY to order it by whatever you want to order your list by. The trick is, to order it descending, instead of ascending.

SELECT * from table
ORDER BY Name desc
LIMIT 1;

Every idle table should have Auto_increment index named INDEX_NO which use to have highest number, then your table would have items this way

INDEX_NO   Name      Age
 1         Alex      23
 2         Tom       24

and then you can use this query and i can say that this is fast.

SELECT * from table
ORDER BY INDEX_NO desc
LIMIT 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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