2013-12-12 83 views
3

我的查詢有問題,有什麼問題?MySQL病例聲明 - 未知列在哪裏

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 - 在未知列'id_ranking 'where子句'

謝謝!

+0

哪裏犯規看到別名。 – Mihai

回答

4

這是因爲SELECT準備結果(作爲id_ranking)AFTER比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子句
  2. WHERE子句
  3. GROUP BY子句
  4. HAVING子句
  5. SELECT子句
  6. ORDER BY條款
+0

還沒有其他方法可以解決? 「id_ranking(1,2)」這部分是變量 –

+0

這是一個很好的標準方法,但您可以使用其他方法得到一個結果。例如,您可以在WHERE子句中公開CASE,或者選擇到另一個表中,而不是使用當前子句(2個查詢)。但你真的需要這個嗎? – BaBL86

+0

謝謝!我決定在哪裏使用 –

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 
3

,別名不會在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) 
+0

YOR WHERE工作無處不在,因爲1,2和3始終<300 – BaBL86

+0

@ BaBL86:true,正在修復 – a1ex07