我的查询有问题,出了什么问题?
SELECT
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END as id_ranking
FROM cp_pessoa
WHERE id_ranking IN (1,2);
我收到此错误:#1054 - 'where子句'中的未知列'id_ranking'
谢谢!
答案 0 :(得分:4)
这是因为SELECT准备结果(作为id_ranking)比调用WHERE更早。
SELECT
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END as id_ranking
FROM cp_pessoa
WHERE cp_pessoa.score < 300;
这是如何工作的(订单):
答案 1 :(得分:4)
where
中不允许使用别名。将查询更改为
SELECT * FROM
(
SELECT
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END as id_ranking
FROM cp_pessoa
)a
WHERE id_ranking IN (1,2)
或
SELECT
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END as id_ranking
FROM cp_pessoa
WHERE
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END IN (1,2)
答案 2 :(得分:0)
您不能在where子句中使用别名,而是尝试
SELECT
CASE
WHEN cp_pessoa.score < 100 THEN 1
WHEN cp_pessoa.score < 300 THEN 2
WHEN cp_pessoa.score >= 300 THEN 3
END as id_ranking
FROM cp_pessoa
WHERE cp_pessoa.score < 300