Are subqueries the only option to reuse variables?

孤街醉人 提交于 2019-12-25 04:36:16

问题


I'd like to use MySQL in this form:

SELECT 1 AS one, one*2 AS two

because it's shorter and sweeter than

SELECT one*2 AS two FROM ( SELECT 1 AS one ) AS sub1

but the former doesn't seem to work because it expects one to be a column.

Is there any easier way to accomplish this effect without subqueries?

And no, SELECT 2 AS two is not an option. ;)


回答1:


select @one := 1 as one, 2 * @one as two;

user-defined variables




回答2:


Considering this SQL code

SELECT 1 AS one, one*2 AS two

from the perspective of SQL the language (and why not; mysql has a good track record of compliance with the ISO/ANSI SQL Standards), your one is not a variable; rather it is a column correlation name. You cannot use the correlation name in the SELECT clause with the same scope, hence the error.

FWIW your 'shorter and sweeter' syntax does actually work when using the MS Access Database Engine -- is that where you learned it, perchance? Sadly, the Access Database Engine has a poor track record of compliance with the Standards. It is said to take a long time to un-learn Access-speak and learn SQL code ;)



来源:https://stackoverflow.com/questions/1669498/are-subqueries-the-only-option-to-reuse-variables

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