Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select distinct rows into a comma delimited list column

Tags:

sql

mysql

I currently have some sql that brings back tags. they should have distinct ids, but they don't.... so my current data is like:

Microsoft | GGG | 1 | 167
Microsoft | GGG | 1 | 2
Microsoft | GGG | 1 | 1

What i would like to do is have only one row come back with the final column concatenated into a delimited list like:

Microsoft | GGG | 1 | 167, 2, 1

I am using mySQL 5 for this.

like image 409
Jarede Avatar asked Dec 01 '11 15:12

Jarede


People also ask

How do I select distinct rows in MySQL?

MySQL – Distinct Values To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.

How do I get distinct comma separated values in SQL?

Solution 1. Available in SQL Server 2016 and later. -- Sort the values: SELECT value FROM STRING_SPLIT(@temp, ',') ORDER BY value; -- Remove duplicates: SELECT DISTINCT value FROM STRING_SPLIT(@temp, ',');

How do I get comma separated values in MySQL?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.


1 Answers

Use GROUP_CONCAT() for this, with a GROUP BY covering the other three columns:

SELECT 
  name,   -- Microsoft
  other,  -- GGG
  other2, -- 1
  GROUP_CONCAT(id) AS ids
FROM tbl
GROUP BY name, other, other2
like image 130
Michael Berkowski Avatar answered Sep 16 '22 16:09

Michael Berkowski