首页 > 解决方案 > 如何在 MySQL 中增加列值的出现次数

问题描述

我有以下列名称:

increment_id并且other_id将是唯一的,customer_email将有重复。当结果返回时,我想知道电子​​邮件的出现次数。

对于每一行,我想知道到目前为止customer_email该值出现了多少次。该字段的末尾会有一个子句,我还计划添加一个 where 子句order bycreated_atwhere occurrences < 2

我正在查询 > 500 万行,但性能并不是重要,因为我将把它作为生产环境中的只读副本数据库的报告运行。在我的用例中,我会牺牲性能来换取鲁棒性。

| customer_email | incremenet_id | other_id | created_at          | occurances <- I want this |
|----------------|---------------|----------|---------------------|---------------------------|
| joe@test.com   | 1             | 81       | 2019-11-00 00:00:00 | 1                         |
| sue@test.com   | 2             | 82       | 2019-11-00 00:01:00 | 1                         |
| bill@test.com  | 3             | 83       | 2019-11-00 00:02:00 | 1                         |
| joe@test.com   | 4             | 84       | 2019-11-00 00:03:00 | 2                         |
| mike@test.com  | 5             | 85       | 2019-11-00 00:04:00 | 1                         |
| sue@test.com   | 6             | 86       | 2019-11-00 00:05:00 | 2                         |
| joe@test.com   | 7             | 87       | 2019-11-00 00:06:00 | 3                         |

标签: mysqlsqlmysql-5.6

解决方案


您可以在早期版本的 MySQL 中使用变量:

select t.*,
       (@rn := if(@ce = customer_email, @rn + 1,
                  if(@ce := customer_email, 1, 1)
                 )
       ) as occurrences
from (select t.*
      from t
      order by customer_email, created_at
     ) t cross join
     (select @ce := '', @rn := 0) params;

在 MyQL 8+ 中,我建议row_number()

select t.*,
       row_number() over (partition by customer_email order by created_at) as occurrences
from t;

推荐阅读