SQL错误 - 列不存在(在SELECT中)

时间:2016-12-31 14:06:23

标签: sql postgresql activerecord

我正在加入两个表:品种 + 品种特征(bc)

但我收到以下错误:

  

PG :: UndefinedColumn:ERROR:列“val”不存在LINE 11

我不确定是什么问题,这是我的SQL:

SELECT                                                                      
  breeds.*,                                                                 
  CASE bc.user_val                                                          
    WHEN NULL THEN bc.value                                                   
     ELSE (bc.value + (bc.user_val/2))/2                                       
   END AS val                                                                
  FROM                                                                        
  breed_characteristics bc       
  INNER JOIN breeds ON breeds.id = bc.breed_id                                
  WHERE bc.characteristic_id = 45                               
  AND val BETWEEN 4 AND 5                              
  ORDER BY val DESC

(通过Active Record在Postgres上执行此查询)

2 个答案:

答案 0 :(得分:6)

您不能在val子句中使用表达式别名where

这是因为在SQL标准中指定了执行SQL的顺序。这里,WHERE子句在SELECT之前被评估,因此WHERE子句不知道您在SELECT中创建的别名。 ORDER BY位于SELECT之后,因此可以使用别名。

只需将别名替换为实际的case表达式,如下所示:

SELECT                                                                      
  breeds.*,                                                                 
  CASE bc.user_val                                                          
    WHEN NULL THEN bc.value                                                   
     ELSE (bc.value + (bc.user_val/2))/2                                       
   END AS val                                                                
  FROM                                                                        
  breed_characteristics bc       
  INNER JOIN breeds ON breeds.id = bc.breed_id                                
  WHERE bc.characteristic_id = 45                               
  AND CASE WHEN bc.user_val is NULL THEN bc.value                                                   
     ELSE (bc.value + (bc.user_val/2))/2                                       
   END BETWEEN 4 AND 5                              
  ORDER BY val DESC

但是,您可以在order by子句中使用别名。

答案 1 :(得分:2)

避免在多个地方重述CASE表达式的一个选项是使用子查询:

SELECT *
FROM
(
    SELECT b.*,
           bc.characteristic_id,
           CASE WHEN bc.user_val IS NULL THEN bc.value
                ELSE (bc.value + (bc.user_val / 2)) / 2                                       
           END AS val                            
    FROM breed_characteristics bc       
    INNER JOIN breeds b
        ON breeds.id = bc.breed_id
) t
WHERE t.characteristic_id = 45 AND
      t.val BETWEEN 4 AND 5                              
ORDER BY t.val DESC