Add row numbers for sorted data in MySQL
When working with sorted data in MySQL, getting the row number for each record can enhance the information provided and facilitate more detailed analysis. This article explores how to achieve this using pure SQL, providing a solution that avoids post-processing in Java or other programming languages.
Database table structure
Consider the following table named "orders" with the fields "orderID" and "itemID":
<code class="language-sql">mysql> describe orders; +-------------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------------+------+-----+---------+----------------+ | orderID | bigint(20) unsigned | NO | PRI | NULL | auto_increment | | itemID | bigint(20) unsigned | NO | | NULL | | +-------------+---------------------+------+-----+---------+----------------+</code>
Original query
Initially, use query to get the order count for each itemID:
<code class="language-sql">SELECT itemID, COUNT(*) as ordercount FROM orders GROUP BY itemID ORDER BY ordercount DESC;</code>
Add line number
In order to add the row number, you can modify the query as follows:
<code class="language-sql">SET @rank=0; SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount FROM orders GROUP BY itemID ORDER BY ordercount DESC; SELECT @rank;</code>
Description
Improved results
Running the modified query will provide the following enhanced results:
<code>+------+--------+------------+ | rank | itemID | ordercount | +------+--------+------------+ | 1 | 388 | 3 | | 2 | 234 | 2 | | 3 | 3432 | 1 | | 4 | 693 | 1 | | 5 | 3459 | 1 | +------+--------+------------+</code>
As you can see, each row now has an extra "rank" column indicating its position in the sorted result set.
The above is the detailed content of How to Add Row Numbers to Sorted Data in MySQL?. For more information, please follow other related articles on the PHP Chinese website!