Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-02 16:18:02
Original
472 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!