Home > Database > Mysql Tutorial > How to Select Distinct Columns with Corresponding Values in MySQL?

How to Select Distinct Columns with Corresponding Values in MySQL?

DDD
Release: 2024-12-31 08:05:10
Original
772 people have browsed it

How to Select Distinct Columns with Corresponding Values in MySQL?

Selecting Distinct Columns with Corresponding Values in MySQL

To retrieve unique values from a specific column while also obtaining corresponding data from other columns, such as in the provided example where you want to select distinct first names with their respective IDs and last names, you can utilize MySQL's GROUP BY clause.

The following query achieves this:

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

By grouping the results by the FirstName column, the database will aggregate the rows with duplicate first names and present the first instance of each distinct name along with its corresponding ID and LastName. In this manner, you will obtain a result set that includes only one entry for John, but with the correct ID of 1 and LastName of Doe.

The above is the detailed content of How to Select Distinct Columns with Corresponding Values 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