Distinct Value Selection from Multiple Columns in MySQL
Extracting distinct values from multiple columns in a MySQL table can be challenging. One approach is to use the DISTINCT keyword followed by a list of the columns you wish to select. This ensures that only unique combinations of those columns are returned.
SELECT DISTINCT a, b, c, d FROM my_table;
However, as mentioned in the question, this method does not return each column's distinct values individually. To achieve this, you can utilize the GROUP BY clause.
SELECT a, DISTINCT b FROM my_table GROUP BY a;
This query groups rows by the a column and selects the distinct values of the b column for each group. Repeat this process for each column you wish to retrieve distinct values from.
For example, to get distinct values for all four columns, you would run the following queries:
SELECT a, DISTINCT b FROM my_table GROUP BY a; SELECT DISTINCT c FROM my_table; SELECT DISTINCT d FROM my_table;
By combining the DISTINCT and GROUP BY clauses, you can easily obtain the desired distinct values from multiple columns in your MySQL database.
The above is the detailed content of How to Extract Distinct Values from Multiple Columns in MySQL?. For more information, please follow other related articles on the PHP Chinese website!