Select row position in MySQL ORDER BY
query
Suppose there is a MySQL table with two columns id
and name
, and the goal is to retrieve a single row and its position in the table sorted by the name
column in ascending order. The desired result format is a table with columns id
, position
, and name
.
To do this, you can use a subquery combined with user variables:
<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>
In this query, the subquery calculates the position of each row based on the order of the name
values. User-defined variable @rownum
is used to assign unique positions. The main query then filters the results to get the desired name
value "Beta".
Alternatively, the following query provides rankings that solve cases with the same name:
<code class="language-sql">SELECT t.id, (SELECT COUNT(*) FROM TABLE x WHERE x.name <= t.name) AS position, t.name FROM TABLE t WHERE t.name = 'Beta';</code>
This query calculates the position by counting the number of rows with a name
value less than or equal to the current row's name
value. Both methods provide a way to determine the position of rows in a sorted result set.
The above is the detailed content of How to Get the Row Position of a Specific Entry in a MySQL `ORDER BY` Query?. For more information, please follow other related articles on the PHP Chinese website!