Home >Database >Mysql Tutorial >How to Retrieve DISTINCT Values with Associated Columns in MySQL?

How to Retrieve DISTINCT Values with Associated Columns in MySQL?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 11:40:14975browse

How to Retrieve DISTINCT Values with Associated Columns in MySQL?

Getting DISTINCT Results with Associated Columns in MySQL

In MySQL, if you need to retrieve unique values from a particular column (e.g., FirstName) while ensuring that corresponding values from other columns (e.g., ID and LastName) are preserved, you cannot simply use the DISTINCT keyword.

For instance, consider the following table:

ID   FirstName   LastName<br>1      John        Doe<br>2      Bugs        Bunny<br>3      John        Johnson<br>

If you want to retrieve distinct FirstName values, you might be tempted to use DISTINCT like this:

SELECT DISTINCT FirstName FROM table;

However, this approach only returns the FirstName column and does not provide the corresponding ID and LastName values.

To achieve the desired result, you can leverage the GROUP BY clause as follows:

SELECT ID, FirstName, LastName
FROM table
GROUP BY FirstName;

In this query, FirstName is specified as the grouping column. As a result, only one row is returned for each distinct FirstName value. Furthermore, the query retrieves the corresponding ID and LastName values from the first occurrence of each FirstName.

Using this approach, the result set would appear as follows:

ID   FirstName   LastName<br>1      John        Doe<br>2      Bugs        Bunny<br>

This solution ensures that you obtain unique FirstName values while maintaining the association with the correct ID and LastName.

The above is the detailed content of How to Retrieve DISTINCT Values with Associated Columns 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