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