mysql select distinct comma delimited values

旧巷老猫 提交于 2020-12-12 06:57:53

问题


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


回答1:


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




回答2:


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)));


来源:https://stackoverflow.com/questions/44546968/mysql-select-distinct-comma-delimited-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!