How to obtain the record row number in the MySQL query result set

Source: Internet
Author: User

If you need to include a column in the column returned by the query statement to indicate the row number of the record in the entire result set, the method proposed by the iso SQL: 2003 Standard is to provide ROW_NUMBER ()/RANK () function. Oracle can use the standard method 8i or later), you can also use 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 thatMySQLI have long wanted to add this feature, 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.

Edit recommendations]
 

Related Article

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.