Selecting the First Row for Each Group in MySQL
To select the first row for each group in MySQL, you could utilize the concept of subqueries. First, identify the primary keys of the columns of interest by using the following subquery:
<code class="sql">SELECT MIN(id) FROM sometable GROUP BY somecolumn</code>
Once you have the primary keys, you can employ another subquery to retrieve the desired data:
<code class="sql">SELECT somecolumn, anothercolumn FROM sometable WHERE id IN ( SELECT MIN(id) FROM sometable GROUP BY somecolumn );</code>
This approach is incompatible with the T-SQL code provided in the question, as it utilizes specific syntax supported by Microsoft SQL Server. However, the subquery method is an effective way to select the first row for each group in MySQL.
The above is the detailed content of How to Select the First Row for Each Group in MySQL?. For more information, please follow other related articles on the PHP Chinese website!