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:
SELECT DISTINCT foo, bar FROM foo_bar;
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:
SELECT foo, bar FROM foo_bar GROUP BY foo, bar;
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3