我有一个查询,按月或按天计算用户总数。所以我要做的就是在一个变量中累积这个总数。我的代码是:
select * from (select createdDate,newUsers, ( csum := csum + newUsers ) as totalUsers
from (
select IF(STRCMP(@byType,'month')=0,DATE_FORMAT(dtCreatedDate,'%Y-%m'),dtCreatedDate) as createdDate,
count(dtCreatedDate) as newUsers
from Users u
group by IF(STRCMP(@byType,'month')=0,DATE_FORMAT(dtCreatedDate,'%Y-%m'),dtCreatedDate)
) as temp order by createdDate) as temp2
where createdDate BETWEEN IF(
STRCMP(@byType,'month')=0,DATE_FORMAT(dateOne,'%Y-%m'),dateOne)
and IF(STRCMP(@byType,'month')=0,DATE_FORMAT(dateTwo,'%Y-%m'),dateTwo);
我的问题是我无法使用该语句csum := csum + newUsers
,因为我收到此语法错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= csum + newUsers)
from (
select IF(STRCMP(@by' at line 16
csum = csum + newUsers
如果我使用并且我已经尝试使用但它似乎没有效果,则可以避免该语法错误csum = csum + newUsers
,因为 csum 始终为 0。我也尝试使用select csum = csum + newUsers
orselect csum := csum + newUsers
但没有任何效果。
我使用了selec into
这样的:select (csum + newUsers) into csum
而且我还得到了下一个错误:
Misplaced INTO clause, INTO is not allowed inside subqueries, and must be placed at end of UNION clauses.
我知道我可以使用用户定义的变量,@csum := @csum + newUsers
但我收到下一条警告消息:
Setting user variables within expressions is deprecated and will be removed in a future release.
Consider alternatives: 'SET variable=expression, ...', or 'SELECT expression(s) INTO variables(s)'.
所以,我想知道是否有一种方法可以在不使用的情况下解决我的问题user-defined variables