2015-10-07 147 views
1

問表:如何計算逗號分隔列中的出現次數?

id   | tags 
-------------------------------------- 
1   | css,javascript,html 
2   | mysql,sql,html 
3   | css,spring,php  
4   | css,java,html 

我試圖找出如何返回每個標籤的發生串的次數。

結果表:

tags   | count 
-------------------------------------- 
css   | 3 
html   | 3 
javascript | 1  
php   | 1 

回答

2

您可以使用:

SqlFiddleDemo

SELECT sub.val AS tags, COUNT(*) AS `count` 
FROM 
(
    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.tags, ',', n.n), ',', -1) AS val 
    FROM tab 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.tags) - LENGTH(REPLACE(t.tags, ',', ''))) 
) sub 
GROUP BY sub.val 
+1

你的答案是如此之大,比你這麼多,這是我想要的...... – theinlwin

+0

同樣的價值如何計數? – theinlwin

+0

@theinlwin我不會翹首以待您的最後一個問題 – lad2025

2

您可以簡單地嘗試這樣的:

SELECT COUNT(*) FROM my_table WHERE tags like '%css%'; 
SELECT COUNT(*) FROM my_table WHERE tags like '%html%'; 
SELECT COUNT(*) FROM my_table WHERE tags like '%javascript%'; 
SELECT COUNT(*) FROM my_table WHERE tags like '%php%'; 

的另一種方式是使用這樣的:

(LENGTH(`tags`) - LENGTH(REPLACE(`tags`, 'searchword', '')))/LENGTH('searchword') 
+0

謝謝,但我想同樣的值每個計數形式表內 – theinlwin

+0

@theinlwin: - '但我想同樣的值每個計數形式表inside'我不知道你是什麼意思? –

+0

:請參閱http://sqlfiddle.com/#!2/eeda7/9 – theinlwin