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 ISOSQL: 2003 Standard is to provide the ROW_NUMBER () RANK () function. Standard methods (8i or later) can be used in Oracle, or non-standard ROWNUM can be used. MSSQLServer provides
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. Standard methods can be used in Oracle (8i or later) or non-standard ROWNUM; ms SQL Server provides
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. 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.