2016-11-15 83 views
-1

如何從MySql中以逗號分隔值存儲的數據中選擇不同的值和相對計數?MYSQL從逗號分隔的不同值計數

這是在表中的數據看起來的樣子:

"Category" "Values"  
"red"   "D,A,D,D"  
"yellow"  "A,A,D,D" 

慾望輸出:

"red" "D" "3"  
"red" "A" "1"  
"yellow" "D" "2"  
"yellow" "A" "2" 

你能想到的在mysql中一個很好的辦法讓我好象路輸出做了什麼? 提前致謝。

+2

是的,我能想到的好方法是使桌子正常化並使其成爲一對多,之後生活將變得簡單。 –

+0

http://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad/3653574 – e4c5

回答

1

使用派生表可以拆分串入行

SELECT `Category`, SUBSTRING_INDEX(SUBSTRING_INDEX(t.`Values`, ',', n.n), ',', -1) `value` 
FROM table1 t CROSS JOIN 
(
    SELECT a.N + b.N * 10 + 1 n 
    FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a 
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b 
    ORDER BY n 
) n 
WHERE n.n <= 1 + (LENGTH(t.`Values`) - LENGTH(REPLACE(t.`Values`, ',', ''))) 

然後,只需GROUP BYCOUNT

DEMO

SELECT `Category`, `value`, COUNT(*) as cnt 
FROM (
    <previous query> 
    ) T 
GROUP BY `Category`, `value` 

enter image description here

+0

只要你知道鞋幫的位置可能值範圍,在這種情況下9.非常好的解決方案胡安卡洛斯。 –