Home >Database >Mysql Tutorial >How to Select the First Row for Each Group in MySQL?

How to Select the First Row for Each Group in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 17:34:02477browse

How to Select the First Row for Each Group in MySQL?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn