MySQL用户定义的变量与COUNT一起使用时返回错误的结果

时间:2016-11-21 10:31:48

标签: mysql variables count defined

我想查找按月分组的特定年份的注册用户数。 以下是查询

set @numberOfUsers := 0; 
SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers, 
(@numberOfUsers := @numberOfUsers + count(u.id)) as totalUsers 
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate));

但是,我没有得到totalUsers的正确结果,它没有添加前一行的结果。

month  |  monthlyUsers  |  totalUsers
10     |       1        |      1
11     |       3        |      3

第11个月的totalUsers值应为4.不确定查询中有什么问题。 有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

您应该在子查询中嵌入GROUP BY查询,以计算最终结果的运行总计,而不是在计数仍未计算时#34; :

set @numberOfUsers := 0; 
SELECT T.*, (@numberOfUsers := @numberOfUsers + T.monthlyusers) as totalUsers 
FROM  
(
    SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers
    FROM user u 
    where year(from_unixtime(u.createdDate)) = '2016' 
    group by month(from_unixtime(u.createdDate))
) T;

答案 1 :(得分:0)

阅读以下内容:http://dev.mysql.com/doc/refman/5.7/en/user-variables.html

  

对于其他语句,例如SELECT,您可能会得到您期望的结果,但这不能保证。在下面的语句中,您可能会认为MySQL将首先评估@a,然后再进行一次分配:

以下代码应作为解决方案(使用子查询):

SELECT month(from_unixtime(u.createdDate)) as month, 
       count(u.id) as monthlyusers, 
       (select count(*) from user USER where year(USER.createdDate)='2016' and month(USER.createdDate)<=month(u.createdDate)) as totalUsers
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate));