Home >Database >Mysql Tutorial >How to Retrieve the First Row of Each Group in MySQL?

How to Retrieve the First Row of Each Group in MySQL?

DDD
DDDOriginal
2024-11-04 18:36:01472browse

How to Retrieve the First Row of Each Group in MySQL?

Extracting First Rows from Groups in MySQL

You're seeking a way to retrieve the first row for each group in MySQL. While the C# and Linq-To-Sql approaches provided are incompatible with MySQL, we can utilize a different technique.

In MySQL, you can employ subselects to achieve this:

  1. Begin by obtaining a list of primary keys for the rows you're interested in:

    <code class="sql">SELECT min(id) 
    FROM sometable 
    GROUP BY somecolumn</code>
  2. Subsequently, utilize this set of primary keys to filter and select the data you require:

    <code class="sql">SELECT somecolumn, anothercolumn 
    FROM sometable 
    WHERE id IN (
       SELECT min(id) 
       FROM sometable 
       GROUP BY somecolumn
    );</code>

This method allows you to retrieve the first row for each group without the need for complex T-SQL translations.

The above is the detailed content of How to Retrieve the First Row of 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