Home > Database > Mysql Tutorial > How to Extract Distinct Values from Multiple Columns in MySQL?

How to Extract Distinct Values from Multiple Columns in MySQL?

Linda Hamilton
Release: 2024-12-29 10:22:15
Original
322 people have browsed it

How to Extract Distinct Values from Multiple Columns in MySQL?

Distinct Value Selection from Multiple Columns in MySQL

Extracting distinct values from multiple columns in a MySQL table can be challenging. One approach is to use the DISTINCT keyword followed by a list of the columns you wish to select. This ensures that only unique combinations of those columns are returned.

SELECT DISTINCT a, b, c, d
FROM my_table;
Copy after login

However, as mentioned in the question, this method does not return each column's distinct values individually. To achieve this, you can utilize the GROUP BY clause.

SELECT
  a, DISTINCT b
FROM my_table
GROUP BY a;
Copy after login

This query groups rows by the a column and selects the distinct values of the b column for each group. Repeat this process for each column you wish to retrieve distinct values from.

For example, to get distinct values for all four columns, you would run the following queries:

SELECT
  a, DISTINCT b
FROM my_table
GROUP BY a;

SELECT
  DISTINCT c
FROM my_table;

SELECT
  DISTINCT d
FROM my_table;
Copy after login

By combining the DISTINCT and GROUP BY clauses, you can easily obtain the desired distinct values from multiple columns in your MySQL database.

The above is the detailed content of How to Extract Distinct Values 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