这个问题在这里已有答案:
我有一个存储数据的表,如:
userid books
ym0001 dictionary,textbooks,notebooks
ym0002 textbooks,dictionary
我想计算每本书发生的次数。我希望我的结果是这种格式。
books Counts
dictionary 2
notebooks 1
textbooks 2
这是mysql。请帮忙
以下方法构建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
db <>小提琴here