0

我有一个问题。我试图在我的 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”

有人知道如何使它工作吗?

提前致谢。

4

3 回答 3

3

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

但是,由于您使用的是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"
于 2012-09-18T20:39:02.103 回答
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
于 2012-09-18T20:24:39.600 回答
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
于 2012-09-18T20:26:22.613 回答