如何计算逗号分隔列中的出现次数?

时间:2015-10-07 06:48:27

标签: mysql string-split

问题表:

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 个答案:

答案 0 :(得分: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')

答案 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