MySQL Case Statement - 其中的未知列

时间:2013-12-12 19:56:43

标签: mysql sql case

我的查询有问题,出了什么问题?

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'

谢谢!

3 个答案:

答案 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. FROM clause
  2. WHERE子句
  3. GROUP BY子句
  4. HAVING条款
  5. SELECT条款
  6. ORDER BY子句

答案 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