Efficiently obtain row positions after MySQL sorting
In a MySQL table, determining the position of a specific row after sorting based on a specific column (e.g. 'name') requires an optimized approach to avoid loading a large result set.
Consider the following query:
<code class="language-sql">SELECT x.id, x.position, x.name FROM (SELECT t.id, t.name, @rownum := @rownum + 1 AS position FROM TABLE t JOIN (SELECT @rownum := 0) r ORDER BY t.name) x WHERE x.name = 'Beta'</code>
This query uses a subquery to assign row positions based on the ORDER BY clause and then filters the required row 'Beta'. The position is calculated using the @rownum user variable, which is automatically incremented for each row.
Alternatively, you can use the following query to handle the tie differently:
<code class="language-sql">SELECT t.id, (SELECT COUNT(*) FROM TABLE x WHERE x.name < t.name) + 1 AS position FROM TABLE t WHERE t.name = 'Beta'</code>
This method returns the same position for parallel rows and may provide a different result set than the first query.
The above is the detailed content of How Can I Efficiently Find the Row Position in MySQL After Ordering?. For more information, please follow other related articles on the PHP Chinese website!