子查询是重用变量的唯一选择吗?

发布于 2024-08-10 11:41:17 字数 298 浏览 6 评论 0原文

我想以这种形式使用 MySQL:

SELECT 1 AS one, one*2 AS two

因为它比前者更短、更甜蜜,

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

但前者似乎不起作用,因为它期望一个是一列。

有没有更简单的方法可以在不使用子查询的情况下实现这种效果?

不,SELECT 2 AS Two 不是一个选项。 ;)

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. ;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜嗑 2024-08-17 11:41:17

从 SQL 语言的角度考虑此 SQL 代码

SELECT 1 AS one, one*2 AS two

(为什么不呢;mysql 在遵守 ISO/ANSI SQL 标准方面有着良好的记录),您的 one 不是一个变量;而是一个变量。相反,它是一个列关联名称。您不能在具有相同范围的 SELECT 子句中使用相关名称,因此会出现错误。

FWIW,您的“更短更甜”语法在使用 MS Access 数据库引擎时实际上确实有效 - 也许您是从那里学到的?遗憾的是,Access 数据库引擎在遵守标准方面的记录不佳。据说要花很长时间才能忘记Access-speak并学习SQL代码;)

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 ;)

忱杏 2024-08-17 11:41:17
select @one := 1 as one, 2 * @one as two;

用户定义变量

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

user-defined variables

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文