"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Select Distinct Value Combinations from Multiple Columns in MySQL?

How to Select Distinct Value Combinations from Multiple Columns in MySQL?

Published on 2024-11-17
Browse:906

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":

foobar
ac
cf
da
ca
fc
ac
da
ac
ca
fc

Querying this table with the following SQL statement:

SELECT DISTINCT foo, bar FROM foo_bar;

produces the following result:

foobar
ac
cf
da
ca
fc

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:

foobar
ac
cf
da

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.

Latest tutorial More>

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