Home >Database >Mysql Tutorial >How to Select Distinct Value Combinations from Multiple Columns in MySQL?
Selecting Distinct Values from Multiple Columns in MySQL
When working with databases, it's often necessary to retrieve unique combinations of values from multiple columns. However, using the DISTINCT keyword may not always yield the desired results. This article explores an alternative approach to selecting distinct values from two columns in a MySQL database.
Consider the following table named "foo_bar":
foo | bar |
---|---|
a | c |
c | f |
d | a |
c | a |
f | c |
a | c |
d | a |
a | c |
c | a |
f | c |
Querying this table with the following SQL statement:
<code class="sql">SELECT DISTINCT foo, bar FROM foo_bar;</code>
produces the following result:
foo | bar |
---|---|
a | c |
c | f |
d | a |
c | a |
f | c |
While this query ensures that only one instance of each unique value combination is returned, it doesn't eliminate the redundancies where the values are swapped in the two columns. For example, both "a c" and "c a" are distinct combinations, but they refer to the same data.
To address this issue, we can use the GROUP BY clause instead:
<code class="sql">SELECT foo, bar FROM foo_bar GROUP BY foo, bar;</code>
This query returns the following result:
foo | bar |
---|---|
a | c |
c | f |
d | a |
As you can see, the GROUP BY clause combines all duplicate rows into a single row, effectively eliminating the repetitions and providing truly distinct combinations of values from both the foo and bar columns.
The above is the detailed content of How to Select Distinct Value Combinations from Multiple Columns in MySQL?. For more information, please follow other related articles on the PHP Chinese website!