What should I do if I want to get the record row number in the MySQL query result set? The following describes how to obtain the row number of a record in a MySQL query result set. We hope you will be enlightened.
Used to calculate the position of a specific record in the query result.
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 MySQL query 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 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.
Implementation of MySQL random Query
Optimization of MySQL query Paging
Use variables to query row numbers in MySQL
MySQL query results are sorted by a certain value
Non-empty question in MySQL Query