我正在加入两个表:品种 + 品种特征(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上执行此查询)
答案 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