简体   繁体   English

如何计算 MySQL 中逗号分隔字符串中 substring 的出现次数

[英]How to count occurrence of a substring in a comma separated string in MySQL

Let's say I have selected records like this假设我选择了这样的记录

+----+-------------------------------------------------------------------------------------
| id | groupedStatus                                                                      |
+----+-------------------------------------------------------------------------------------
| 1 | received,accepted,discarded,discarded,accepted,discarded,accepted,received,received |
| 2 | accepted,discarded,received,received,received,received,received                     |          
+----+-------------------------------------------------------------------------------------

Along with the above records, I also want to get the occurrence of each substring in the groupedStatus string,除了上面的记录,我还想得到groupedStatus字符串中每个substring的出现,

for example, in the first row, the occurrences are as follows:例如,在第一行中,出现如下:

received: 3 accepted: 3 discarded: 3收到:3 接受:3 丢弃:3

Original Table Schema原始表架构

Table1表格1

ID int

Table 2:表 2:

ID
Table1ID
Status enum('received','accepted','discarded') 

I am selecting above records using the following query我正在使用以下查询选择上述记录

select t1.id, group_concat(t2.status) as groupedStatus from Table1 t1 inner join Table2 t2 on t1.id=t2.table1ID group by t1.id

You can do this with conditional aggregation, like so:您可以使用条件聚合来执行此操作,如下所示:

select 
    t1.id, 
    sum(t2.status = 'received')  as received,
    sum(t2.status = 'accepted')  as accepted,
    sum(t2.status = 'discarded') as discarded,
    group_concat(t2.status) as groupedStatus 
from table1 t1 
inner join table2 t2 on t1.id = t2.table1ID 
group by t1.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM