如何通过CASE语句中的变量对结果进行排序

时间:2018-12-11 18:55:04

标签: mysql

如何通过promotion_price语句中的变量CASE对结果进行排序。我得到的错误是:

Unknown column 'promotion_price' in 'where clause'

这是我的查询:

SELECT product.*,
    CASE
        WHEN promotion.type=1 THEN product.price - (product.price * promotion.value/100)
        WHEN promotion.type=2 THEN product.price - promotion.value
        ELSE product.price
    END promotion_price
FROM product LEFT JOIN page ON product.category_id=page.id
LEFT JOIN promotion_product ON product.id=promotion_product.main_product_id
LEFT JOIN promotion ON promotion_product.promo_id=promotion.id 
WHERE (page.id = 12 OR page.id_in = 12) 
AND promotion_price >= 49.50 
AND promotion_price <= 108.89
GROUP BY product.id
ORDER BY  promotion_price ASC

谢谢!

2 个答案:

答案 0 :(得分:1)

我们知道,我们不能在单个SQL的where子句中使用内联列,您可以使用子查询尝试以下内容。

SELECT * 
FROM
    (SELECT 
         CASE
            WHEN promotion.type = 1 
               THEN product.price - (product.price * promotion.value/100)
            WHEN promotion.type = 2 
               THEN product.price - promotion.value
            ELSE product.price
        END promotion_price,
        product.*
    FROM
        product 
    LEFT JOIN 
        page ON product.category_id = page.id
    LEFT JOIN 
        promotion_product ON product.id = promotion_product.main_product_id
    LEFT JOIN 
        promotion ON promotion_product.promo_id = promotion.id 
    WHERE 
        (page.id = 12 OR page.id_in = 12)
    GROUP BY 
        product.id) s
WHERE
    promotion_price >= 49.50 
    AND promotion_price <= 108.89
ORDER BY  
    promotion_price ASC

答案 1 :(得分:1)

在必须重复代码的条件下不能使用列别名

SELECT product.*,
    CASE
        WHEN promotion.type=1 THEN product.price - (product.price * promotion.value/100)
        WHEN promotion.type=2 THEN product.price - promotion.value
        ELSE product.price
    END promotion_price
FROM product LEFT JOIN page ON product.category_id=page.id
LEFT JOIN promotion_product ON product.id=promotion_product.main_product_id
LEFT JOIN promotion ON promotion_product.promo_id=promotion.id 
WHERE (page.id = 12 OR page.id_in = 12) 
AND (CASE
        WHEN promotion.type=1 THEN product.price - (product.price * promotion.value/100)
        WHEN promotion.type=2 THEN product.price - promotion.value
        ELSE product.price
    END ) >= 49.50 
AND (CASE
        WHEN promotion.type=1 THEN product.price - (product.price * promotion.value/100)
        WHEN promotion.type=2 THEN product.price - promotion.value
        ELSE product.price
    END) <= 108.89
GROUP BY product.id
ORDER BY  promotion_price ASC

在评估select列别名之前先评估where条件,因此在查询where条件时查询引擎不知道select列别名