Home  >  Article  >  Database  >  How to Select Distinct Values from Two Columns in MySQL and Eliminate Duplicate Entries?

How to Select Distinct Values from Two Columns in MySQL and Eliminate Duplicate Entries?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:20:031097browse

How to Select Distinct Values from Two Columns in MySQL and Eliminate Duplicate Entries?

Selecting Distinct Values from Two Columns in MySQL: Overcoming Duplicate Entries

In MySQL database management, distinguishing duplicate values across multiple columns can present a challenge. Consider the following scenario:

Question:

A database table named 'foo' contains two columns, 'foo' and 'bar', with the following data:

foo bar
a c
c f
d a
c a
f c
a c
d a
a c
c a
f c

When executing the query "SELECT DISTINCT foo, bar FROM foo", the following results are obtained:

foo bar
a c
c f
d a
c a
f c

However, these results include repeated pairings of 'foo' and 'bar' values, such as 'a' and 'c', which appear in different orders. The goal is to select only distinct values from both columns, eliminating these duplicates.

Answer:

To address this issue, MySQL provides the 'GROUP BY' clause, which groups rows based on specified columns and selects only one distinct row for each group. By using this clause, we can modify the query as follows:

SELECT foo, bar
FROM foo
GROUP BY foo, bar;

This modified query will produce the following results:

foo bar
a c
c f
d a

By grouping rows by both 'foo' and 'bar', the query ensures that each distinct combination of values is represented only once in the results, regardless of the order in which they appear.

The above is the detailed content of How to Select Distinct Values from Two Columns in MySQL and Eliminate Duplicate Entries?. For more information, please follow other related articles on the PHP Chinese website!

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