在相同的SELECT子句中使用列别名

时间:2015-03-04 16:56:47

标签: mysql

无论如何在同一个SELECT子句中使用列别名?例如:

SELECT ord_id, candy_id, price, quantity, 
price * quantity AS ext_cost, ext_cost * @tax_rate

返回错误,因为MySQL无法识别" ext_cost"在ext_cost * @tax_rate查询中。如果不可能,可以返回一个包含第一个查询中列出的所有内容的表,而不必写这样的内容吗?

SELECT ord_id, candy_id, price, quantity, 
price * quantity AS ext_cost, (price * quantity) * @tax_rate

基本上,我只是想知道是否在SELECT查询中重用ext_cost

3 个答案:

答案 0 :(得分:7)

不存在引用别名的方法,但您可以将表达式分配给变量,然后引用同一select子句中的变量。

在select语句中,变量赋值始终由中缀运算符:=完成。 *在SET声明中,它可以是=:=

e.g。

SELECT 
    ord_id
  , candy_id
  , price
  , quantity
  , @exc_cost := price * quantity AS exc_cost
  , @exc_cost * @tax_rate AS my_favourite_field
...
<FROM CLAUSE>

您还可以有条件地执行变量赋值。

e.g。

IF(quantity > 90, 
     @exc_cost := price * quantity * 0.95
   , @exc_cost := price * quantity) AS exc_cost

注1:在没有综合措施的情况下group by子句,根据列顺序评估变量:

SELECT @t, @t+2 FROM (SELECT @t := 1) a

产生输出

@t   @t+2
 1      3

答案 1 :(得分:1)

在 MySQL 中,您可以在同一个选择中引用选择列别名,只要它位于引用点之前。

SELECT 
    ord_id,
    candy_id,
    price,
    quantity, 
    price * quantity AS ext_cost,
    (SELECT ext_cost) * @tax_rate as retail_rate

现在如果我知道如何在 postgres 中做到这一点就好了。

答案 2 :(得分:0)

使用子查询

SELECT t1.ord_id, t1.candy_id, t1.price, t1.quantity, t2.ext_cost, t2.ext_cost * @tax_rate
FROM table1 t1
JOIN (SELECT t.ord_id, t.price * t.quantity AS ext_cost FROM table1 t) t2
ON t2.ord_id = t1.ord_id