Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-11-04 18:36:01
Original
402 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template