错误代码:1054未知栏' tzHour'在' where子句'

时间:2015-02-02 15:23:31

标签: mysql mysql-error-1054

尝试让以下工作,尝试调整时区。如果我注释掉行和plan.resetHour = tzHour它会正确显示列tzHour,但似乎不能使用where子句中的值。

SELECT
     `issuer`.`tz`
    ,`account`.`id`
    , `plan`.`endDate`
    , `plan`.`resetDay`
    , `plan`.`resetHour`
    , `plan`.`type`
    , HOUR(NOW())
    ,   CASE issuer.`tz`
        WHEN 'US/Eastern' THEN HOUR(NOW())+1
        WHEN 'US/Central' THEN HOUR(NOW())
        ELSE HOUR(NOW())
    END AS tzHour

FROM
    `dvh`.`account`
    INNER JOIN `dvh`.`plan` 
        ON (`account`.`plan` = `plan`.`id`)
    INNER JOIN `dvh`.`issuer` 
        ON (`plan`.`issuer` = `issuer`.`id`)        
WHERE plan.type='UNIT' 
AND plan.startDate < NOW() 
AND plan.endDate >NOW() 
AND plan.resetDay=DAYOFWEEK(NOW())
AND plan.resetHour=tzHour
AND account.`active`=1;

2 个答案:

答案 0 :(得分:2)

在WHERE子句中使用列别名是非法的。来自MySQL文档:

  

标准SQL不允许在WHERE子句中引用列别名。强制执行此限制是因为在评估WHERE子句时,可能尚未确定列值。

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

解决此问题的一种方法是将案例移到子选项中。

SELECT
     `issuer`.`tz`
    ,`account`.`id`
    , `plan`.`endDate`
    , `plan`.`resetDay`
    , `plan`.`resetHour`
    , `plan`.`type`
    , HOUR(NOW())
    , tempHour.tzHour
FROM 
    (
        SELECT
            CASE `tz`
                WHEN 'US/Eastern' THEN HOUR(NOW())+1
                WHEN 'US/Central' THEN HOUR(NOW())
                ELSE HOUR(NOW())
            END AS tzHour
        FROM issuer
    ) AS tempHour,
    `dvh`.`account`
    INNER JOIN `dvh`.`plan` 
        ON (`account`.`plan` = `plan`.`id`)
    INNER JOIN `dvh`.`issuer` 
        ON (`plan`.`issuer` = `issuer`.`id`)        
WHERE plan.type='UNIT' 
AND plan.startDate < NOW() 
AND plan.endDate >NOW() 
AND plan.resetDay=DAYOFWEEK(NOW())
AND plan.resetHour=tempHour.tzHour
AND account.`active`=1;

答案 1 :(得分:0)

通过将案例移动到where子句

来解决
AND plan.`resetHour` = 
    CASE 
        WHEN issuer.`tz`='US/Eastern' THEN HOUR(NOW())+1
        WHEN issuer.`tz`='US/Central' THEN HOUR(NOW())
        WHEN issuer.`tz`='US/Mountain' THEN HOUR(NOW())-1
        WHEN issuer.`tz`='US/Pacific' THEN HOUR(NOW())-2
    END