MySQL:获取逗号分隔列中的数据计数

时间:2018-10-07 00:09:27

标签: mysql

我有一个存储数据的表,如:

userid    books
ym0001    dictionary,textbooks,notebooks
ym0002    textbooks,dictionary

我想计算每本书出现的次数。我希望我的结果采用这种格式。

books       Counts
dictionary  2
notebooks   1
textbooks   2

这是mysql。请帮助

1 个答案:

答案 0 :(得分:0)

以下方法生成一个1000个整数的结果,然后使用这些整数(n)在逗号分隔的字符串中定位段,并为每个段创建一个新行,以便派生表如下所示:

userid | book      
:----- | :---------
ym0001 | dictionary
ym0002 | textbooks 
ym0001 | textbooks 
ym0002 | dictionary
ym0001 | notebooks 

存在后,只需按书分组即可得出计数。

select
    book, count(*) Counts
from (
    select
           t.userid
         , SUBSTRING_INDEX(SUBSTRING_INDEX(t.books, ',', numbers.n), ',', -1) book
    from (
        select @rownum:=@rownum+1 AS n
        from
        (
           select 0 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
        cross join (
           select 0 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
        cross join  (
           select 0 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
        ) c
        cross join (select @rownum:=0) r
        ) numbers
    inner join mytable t
      on CHAR_LENGTH(t.books)
        -CHAR_LENGTH(REPLACE(t.books, ',', '')) >= numbers.n-1
    ) d
group by
    book
order by
    book
book       | Counts
:--------- | -----:
dictionary |      2
notebooks  |      1
textbooks  |      2
  1. 如果您已经有一个数字表,请改用它。
  2. b和c的交叉联接动态产生1000行,如果需要更多,则添加更多类似于c的交叉联接。即数字数量应超过逗号分隔数据的最大长度

db <>提琴here