Home > Database > Mysql Tutorial > body text

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

Linda Hamilton
Release: 2024-11-05 17:34:02
Original
339 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!