WHERE子句中的别名

时间:2018-01-31 19:02:26

标签: mysql

我试图完成这项工作,我读了一些关于使用子查询的内容,但仍然无法正常工作: 我喜欢使用带有PRECIOFINAL别名的hwere子句。

select 
    NAME,
    PRICE,
    URL,
    STOCK,
    DISCOUNTPERCENTAGE,
    (PRICE-(PRICE*DISCOUNTPERCENTAGE/100)) as PRECIOFINAL 
from PRODUCT P 
left JOIN IMAGE I 
    on P.ID = I.PRODUCT 
left join PROMOTION PR 
    on PR.PRODUCT=P.ID 
where PRECIOFINAL >= 2 
    and PRECIOFINAL <= 20 ;

谢谢!

我想这样做:

Table

价格介于2 - 20之间或者必须显示3件商品,但如果是10件商品只是1件商品,因为它有折扣。

2 个答案:

答案 0 :(得分:1)

不,您不能在WHERE子句中使用别名,而是可以编写子查询

SELECT * FROM
(
  SELECT 
     NAME,
     PRICE,
     URL,
     STOCK,
     DISCOUNTPERCENTAGE,
    (PRICE-(PRICE*DISCOUNTPERCENTAGE/100)) as PRECIOFINAL 
  FROM 
  PRODUCT P left JOIN IMAGE I on P.ID = I.PRODUCT 
  LEFT JOIN PROMOTION PR on PR.PRODUCT=P.ID
)
WHERE PRECIOFINAL >= 2 and PRECIOFINAL <= 20;

答案 1 :(得分:0)

虽然您不能在where子句中使用列别名,但您可以重复以下公式:

select 
    NAME,
    PRICE,
    URL,
    STOCK,
    DISCOUNTPERCENTAGE,
    (PRICE-(PRICE*DISCOUNTPERCENTAGE/100)) as PRECIOFINAL 
from PRODUCT P 
left JOIN IMAGE I 
    on P.ID = I.PRODUCT 
left join PROMOTION PR 
    on PR.PRODUCT=P.ID 
where (PRICE-(PRICE*DISCOUNTPERCENTAGE/100)) BETWEEN 2 AND 20;