Home >Database >Mysql Tutorial >How to Retrieve Distinct Values from One Column While Keeping Corresponding Data in MySQL?

How to Retrieve Distinct Values from One Column While Keeping Corresponding Data in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 12:07:22455browse

How to Retrieve Distinct Values from One Column While Keeping Corresponding Data in MySQL?

DISTINCT Column Retrieval with Corresponding Data in MySQL

In a database table containing multiple columns, such as the one illustrated below:

ID FirstName LastName
1 John Doe
2 Bugs Bunny
3 John Johnson

a common task is to retrieve distinct values from a specific column while maintaining the corresponding data from other columns.

The Objective:

Obtain distinct results from the FirstName column while including the corresponding ID and LastName values. Specifically, only one John should be returned, with an ID of 1 and a LastName of Doe.

The Solution:

To achieve this, the following MySQL query can be employed:

SELECT ID, FirstName, LastName
FROM table
GROUP BY(FirstName)

Query Explanation:

  • The GROUP BY(FirstName) clause categorizes the rows based on the FirstName column.
  • By using this grouping, the query selects the first row within each FirstName category, retaining its ID and LastName values.
  • In the case of duplicate FirstNames, only one row is chosen, ensuring distinct results.

The above is the detailed content of How to Retrieve Distinct Values from One Column While Keeping Corresponding Data 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