如何根据case语句中的变量对结果排序

uqxowvwt  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(391)

如何按变量对结果排序 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

谢谢您!

2eafrhcq

2eafrhcq1#

在必须重复代码的情况下,不能使用列别名

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

where条件是在计算select列别名之前计算的,因此在计算where条件时,查询引擎不知道select列别名

0h4hbjxa

0h4hbjxa2#

我们知道,我们不能在单个sql中使用where子句中的inline列,您可以在subquery中尝试下面的方法。

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

相关问题