How to count occurences in comma separated column?

2019-05-30 15:21发布

问题:

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')