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)
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!