2012-10-24 123 views
0

我不斷收到#1054 - 'where子句'中的未知列'color'。左連接 - 未知列錯誤1054

我的查詢的簡化版本如下。

SELECT *, "red" AS colour 
FROM (
    SELECT *,'calls' AS 'tbl', id AS cid FROM calls) as c 
WHERE colour='red' 
ORDER BY colour ASC, c.created_date DESC 

如果我刪除WHERE行,查詢執行得很好,顏色被識別並且一切正常。

任何幫助,將不勝感激。

+0

我認爲你需要'WHERE status ='2'' –

+1

我更新了你的新查詢的答案 – Marc

+0

我把IF語句拿出來了,仍然沒有運氣。 – hawx

回答

0

這是因爲你不能在你的WHEREORDER BY子句中使用別名

所以,你將不得不做一些像

SELECT *, IF(c.status = '1', "green", "red") AS colour 
FROM (
    SELECT *,'calls1' AS 'tbl', id AS cid FROM calls1 
    WHERE uid LIKE '%1111%' 
    ORDER BY timestamp DESC 
    UNION 
    SELECT *,'calls2' AS 'tbl', id AS cid FROM calls2 
    WHERE uid LIKE '%1111%' 
    ORDER BY timestamp DESC 
) as c 
LEFT JOIN objects AS o ON o.call_id = c.id 
WHERE c.status = 'the color id you want' // or you can rewrite your if here 
ORDER BY c.status ASC, c.timestamp DESC 

或者,這爲您簡化查詢

SELECT *, "red" AS colour 
FROM (
    SELECT *,'calls' AS 'tbl', id AS cid FROM calls) as c 
WHERE c.status = 'the color id you want' 
ORDER BY c.created_date DESC 

爲什麼按顏色分類,如果它總是紅色?

+1

downvote的原因? – Marc

0

試試這個WHERE c.status !='1'

SELECT *, IF(c.status = '1', "green", "red") AS colour 
FROM (
    SELECT *,'calls1' AS 'tbl', id AS cid FROM calls1 
    WHERE uid LIKE '%1111%' 
    ORDER BY timestamp DESC 
    UNION 
    SELECT *,'calls2' AS 'tbl', id AS cid FROM calls2 
    WHERE uid LIKE '%1111%' 
    ORDER BY timestamp DESC 
) as c 
LEFT JOIN objects AS o ON o.call_id = c.id 
WHERE c.status != '1' 
ORDER BY colour ASC, c.timestamp DESC 
2

爲您更新的問題,我認爲你可以做別名

SELECT * FROM (
SELECT *, "red" AS colour 
FROM (
    SELECT *,'calls' AS 'tbl', id AS cid FROM calls) as c 
) as v 
WHERE colour='red' 
ORDER BY colour ASC, v.created_date DESC 
0

使用在where子句是不是一個好方法一欄。請參考以下鏈接。

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html


標準SQL不允許在WHERE子句中的列別名引用。這種限制是強加的,因爲當WHERE子句被評估時,列值可能還沒有被確定。例如,下面的查詢是非法的:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id; 

使用具有的別名或更改條件WHERE子句中使用精確的列名。