我有一个mysql表
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
我需要一个查询来显示来自cid = 28的关键字,但我想只看一次关键字,如(BW,Mercedes,Porsche,Auto,Bmw,Oktober Fest,Germany) 我不想列出2次关键字,如何解决这个问题?
我尝试过不同但却无法得到我想要的东西
答案 0 :(得分:3)
在将所有内容添加到DISTINCT之前拆分它。当然,最好是规范化您的数据(列中的值不超过1)
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
答案 1 :(得分:0)
如果要获取动态输出,则可以使用以下查询在单个记录中获取以逗号分隔的不同值。
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)));