3

i have a mysql table

id      cid    c_name       keywords
 1       28    Stutgart    BW,Mercedes,Porsche,Auto,Germany
 2       34    Roma        Sezar,A.S. Roma
 3       28    München     BMW,Oktober Fest,Auto,Germany

i need a query to show keywords from cid=28 but i want to see only 1 time a keyword, like (BW,Mercedes,Porsche,Auto,Bmw,Oktober Fest,Germany) i dont want to list 2 time a keyword, how can resolve this problem?

i have tried distinct but could not get what i want

Mihai
  • 26,325
  • 7
  • 66
  • 81
Berdan
  • 57
  • 1
  • 9

2 Answers2

8

Split it before adding it all up with DISTINCT.Of course,better is to normalize your data(no more than 1 value in a column)

SELECT
  GROUP_CONCAT( DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(keywords, ',', n.digit+1), ',', -1)) keyword
FROM
  t
  INNER JOIN
  (SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6) n
  ON LENGTH(REPLACE(keywords, ',' , '')) <= LENGTH(keywords)-n.digit
WHERE cid=28

See it working

Mihai
  • 26,325
  • 7
  • 66
  • 81
1

If you want to get a dynamic output then you can use the following query to get a distinct comma delimited values in a single record.

Note: here doesn't matter how many values are in comma delimited row & it's fetched distinct record from a number of rows based on your condition

$tag_list = DB::select('SELECT
                          TRIM(TRAILING "," FROM REPLACE(GROUP_CONCAT(DISTINCT keywords, ","),",,",",")) tag_list
                          FROM
                          test
                          WHERE id = 28');

$unique_tags = implode(',', array_unique(explode(",",$result[0]->search_tags)));
Pinal Patel
  • 122
  • 1
  • 16
  • additional info: keywords = your field name | tag_list = query alias | test = your table | WHERE condition is optional – Abid Khairy Jan 18 '22 at 05:43