How to count occurences in comma separated column?

杀马特。学长 韩版系。学妹 提交于 2019-12-08 03:16:38

问题


Question table:

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

I am trying to figure out how to return the number of times a string occurs in each of the tags's.

Result Table:

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

回答1:


You can use:

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



回答2:


You can simply try like this:

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%';

One other way is to use it like this:

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


来源:https://stackoverflow.com/questions/32985465/how-to-count-occurences-in-comma-separated-column

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