Variable assignment with mysql

我怕爱的太早我们不能终老 提交于 2020-01-06 16:22:32

问题


I use variable assignment with mysql and I found a strange behavior.

See this query :

SET @v1=0;
SET @v2=0;

SELECT @v1, @v2 
FROM MyTable table 
WHERE (@v1:=@v2) is not null 
  AND (@v2:=2) is not null;

I was thinking that conditions are parsed in this order : first (@v1:=@v2) is not null and after (@v2:=2) is not null

and so the result must be :

@v1 | @v2
---------
 0  |  2

But this is not the case. try this query and you will have:

@v1 | @v2
---------
 2  |  2

Why ?


回答1:


SQL is a declarative language, so you cannot assume that your conditions are evaluated in the order you write them. You tell the engine what you want and it is free to determine how to get it.




回答2:


The optimizer does not necessarily keep the order of expressions in WHERE clause the same as your query. You can not depend on any specific order of evaluation




回答3:


The query optimizer is free to rewrite and execute your code in any way it wishes. DO NOT depend on it working in any way that you expect.



来源:https://stackoverflow.com/questions/4924021/variable-assignment-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!