开发者

Mysql user defined variables and COUNT

There is problem with mysql variables and count

The code is below :

SELECT @var := 2, @var := @var+2,
count(birey_dil.birey_id) as count,
@var := @var+count(birey_dil.birey_id), 
@var+1
from birey_dil

Here is result set:

+-----------+----------------+-------+----------------------------------------+--------+
| @var := 2 | @var := @var+2 | count | @var := @var+count(birey_dil.birey_id) | @var+1 |
+-----------+----------------+-------+----------------------------------------+--------+
|         2 |              4 |     8 |                                     12 |      5 |
+-----------+----------------+-------+----------------------------------------+--------+

I set var to 2

and then 2+2 = 4

Then I count the rows and result is 8

@var := @var+count(bir开发者_运维百科ey_dil.birey_id)

Return 4+8 12 but @var+1 is 5

Why mysql acts like that?

The @var+1 should be 13 now and is there a way to fix this?


Try this:
SELECT @var+1 FROM
(
SELECT @var := 2, @var := @var+2,
count(birey_dil.birey_id) as count,
@var := @var+count(birey_dil.birey_id),
from birey_dil
)x
It seems that mysql evaluates all @var[+constant] first; that makes sense because it doesn't require database access, and only then calculates count(birey_dil.birey_id). Finally it does @var := @var+count.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜