在 SQL 计算中使用别名

2021-11-20 00:00:00 sql database syntax mysql

为什么这个查询不起作用?

Why won't this query work?

SELECT 10 AS my_num, my_num*5 AS another_number
FROM table

在本例中,我尝试在其他计算中使用 my_num 别名.这导致未知列my_num"

In this example, I'm trying to use the my_num alias in other calculations. This results in unknown column "my_num"

这是我正在尝试做的简化版本,但基本上我想使用别名进行其他计算.我的计算要复杂得多,这就是为什么最好将其别名化,因为我以不同的方式重复了几次.

This is a simplified version of what I am trying to do, but basically I would like to use an alias to make other calculations. My calculations are much more complicated and thats why it would be nice to alias it since I repeat it several times different ways.

推荐答案

简单地用 (SELECT alias) 包裹你重复使用的别名:

Simply wrap your reused alias with (SELECT alias) :

SELECT 10 AS my_num, 
       (SELECT my_num) * 5 AS another_number
FROM table

相关文章