MySql:在IF / IFNULL中使用别名

时间:2017-04-21 12:32:02

标签: mysql

我发现这篇文章: Using an Alias in SQL Calculations 这表明您可以使用

在计算中使用别名
(select alias)

像:

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

这很好用。但现在我想在if中使用别名。所以我认为它可能会以同样的方式工作。所以我试过了:

SELECT 10 AS my_num, 
       IFNULL(otherfield, (SELECT my_num)) AS another_number
FROM table

根本不起作用,告诉我

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use 
near '(SELECT my_num)) AS another_number

有没有办法在MySql中使这个工作?

1 个答案:

答案 0 :(得分:0)

不,直接使用整个表达式,除非您在外部查询中访问它。

IFNULL(otherfield, 10) AS another_number

在你的情况下它应该是

SELECT 10 AS my_num, 
       IFNULL(otherfield, 10) AS another_number
FROM table