在MySQL中使用IF语句并使用语句的结果进一步计算

时间:2012-09-18 20:19:45

标签: mysql sql if-statement

我有一个问题。我试图在我的SQL查询中使用IF语句,他们在进一步的计算中使用此语句的结果:

SELECT average_rating, number_of_ratings,    
    IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
        IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
            IF(number_of_ratings>1000, 0.99, 0.80)
        )
    ) AS rating_factor,    
    ROUND((rating_factor * average_rating), 4) AS factored_rating    
FROM table
ORDER by factored_rating DESC

但是,它不起作用并返回错误:'字段列表'中的未知列'rating_factor'

有人知道如何让它发挥作用吗?

提前致谢。

3 个答案:

答案 0 :(得分:3)

如果您不需要rating_factor和factored_rating列,Alain的查询将会起作用。 njk的查询是ANSI兼容的subquerying版本。

但是,由于您使用的是 MySQL ,因此可以使用临时变量存储值。我也简化了你的IF条件。

SELECT
    average_rating,
    number_of_ratings,
    @x := IF(number_of_ratings> 1000, 0.99,
          IF(number_of_ratings>=500 , 0.95,
          IF(number_of_ratings> 100 , 0.90,
                                      0.80))) rating_factor,
    ROUND((@x * average_rating), 4) AS factored_rating
FROM mytable
ORDER by factored_rating DESC

这是显示此查询的SQLFiddle 对于后代,样本在下面复制。

drop table if exists mytable;
create table mytable (
average_rating int,
number_of_ratings int,
factored_rating int);
insert into mytable
select 5,2,3 union all
select 4,1,5 union all
select 12,3,1 union all
select 11,4,2 union all
select 8,2,12;

查询结果

"average_rating";"number_of_ratings";"rating_factor";"factored_rating"
"12";"3";"0.80";"9.6000"
"11";"4";"0.80";"8.8000"
"8";"2";"0.80";"6.4000"
"5";"2";"0.80";"4.0000"
"4";"1";"0.80";"3.2000"

答案 1 :(得分:1)

这应该有所帮助:

SELECT a.average_rating, a.number_of_ratings, ROUND((a.rating_factor * a.average_rating), 4) AS factored_rating
FROM
    (SELECT average_rating, number_of_ratings,    
        IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
            IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
                IF(number_of_ratings>1000, 0.99, 0.80)
            )
        ) AS rating_factor   
    FROM table
    ORDER by factored_rating DESC) a

答案 2 :(得分:1)

在公式中使用IF语句的结果。我认为我的问题是正确的,但你应该看到这个想法:

SELECT average_rating, number_of_ratings,    
  ROUND((
    IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
        IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
            IF(number_of_ratings>1000, 0.99, 0.80)
        )
    ) * average_rating), 4) as factored_rating    
FROM table
ORDER by factored_rating DESC