Obtain the record row number in the MySQL Query result set _ MySQL

Source: Internet
Author: User
Obtain the record row number in the MySQL Query result set. if you need to include a column returned by the query statement to indicate the row number of the record in the entire result set, iso SQL: 2003 The method proposed by the standard is to provide the ROW_NUMBER ()/RANK () function. Standard methods (8i or later) can be used in Oracle, or non-standard ROWNUM; ms SQL Server provides the ROW_NUMBER () function in Version 2005; however, MySQL does not seem to have such built-in functions. Although LIMIT can easily filter the number and position of returned result sets, the row numbers of the filtered records cannot be selected. It is said that MySQL has long wanted to add this function, but I haven't found it yet.

The solution is to use predefined user variables:

Set @ mycnt = 0;
Select (@ mycnt: = @ mycnt + 1) as ROWNUM, othercol from tblname order by othercol;

In this way, the row number information is saved in the query result set ROWNUM. The purpose of this row number information is to sort the data according to certain rules and retrieve the sorted data of a row, we also want to know where this row of data is in the previous sorting. For example:

Set @ mycnt = 0;
Select * from (
Select (@ mycnt: = @ mycnt + 1) as ROWNUM, othercol
From tblname order by othercol
) As A where othercol = OneKeyID;

Of course, you can also write the query results to a temporary table with the auto_increment field and perform the query again by creating a temporary table. However, considering the possible problems of the temporary table in MySQL master/slave mode, using this temporary user-defined variable method to calculate the row number corresponding to each row in the query result set is more concise-unless you are willing to process the entire returned result set in PHP or other language scripts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.