Home > Database > Mysql Tutorial > How to Retrieve Unique Values and Corresponding Data in MySQL?

How to Retrieve Unique Values and Corresponding Data in MySQL?

Linda Hamilton
Release: 2024-12-12 12:37:22
Original
555 people have browsed it

How to Retrieve Unique Values and Corresponding Data in MySQL?

Retrieving Unique Values with Corresponding Data in MySQL

In MySQL, distinct values can be retrieved using the DISTINCT keyword. However, when dealing with tables containing multiple columns, it may be necessary to also retrieve corresponding values from other columns based on the distinct values.

For example, consider a table with columns ID, FirstName, and LastName:

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

Our goal is to select distinct values from the FirstName column while also retrieving the corresponding ID and LastName for each unique value. To achieve this, we can use the following query:

SELECT ID, FirstName, LastName
FROM table
GROUP BY(FirstName);
Copy after login

Using the GROUP BY clause, the query groups rows with the same FirstName value. As a result, only the distinct values from the FirstName column will be returned. However, the query also includes the ID and LastName columns in the SELECT list. This ensures that the corresponding ID and LastName values are retrieved for each unique FirstName value.

Executing this query returns the following result set:

ID FirstName LastName
1 John Doe
2 Bugs Bunny

As you can see, the query successfully retrieves the distinct values from the FirstName column while also providing the corresponding ID and LastName values for each distinct value.

The above is the detailed content of How to Retrieve Unique Values and Corresponding Data 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