左连接 - 未知列错误1054

时间:2012-10-24 13:09:40

标签: mysql sql database

我在“where子句”中不断获得#1054 - 未知列'color'。

我的查询的简化版本如下。

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行,查询执行得很好,颜色被识别,一切都很好。

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

如果总是红色,为什么要按颜色排序?

答案 2 :(得分: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

答案 3 :(得分: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;

将HAVING用于别名或更改条件以在WHERE子句中使用确切的列名。