每个派生表都有自己的别名

时间:2016-05-26 06:26:11

标签: mysql

我有以下查询:

select userid, name, checktime, campaign,

CASE WHEN Hoursworked - 9 > 0 THEN Hoursworked - 9 ELSE 0 END Overtime
from
(

    select  
    a.userid,a.name,a.campaign,

    date(a.CHECKTIME),
    timediff(max(b.CHECKTIME), min(a.CHECKTIME)) as Hoursworked
    from CHECKINOUT a

    join CHECKINOUT b

    on date(a.CHECKTIME) = date(b.CHECKTIME) and a.userid = b.userid
    where
    a.CHECKTYPE = 'I'

    AND b.CHECKTYPE = 'O'

    group by date(a.CHECKTIME), userid
)

并且发出此错误

1248 - 每个派生表必须有自己的别名

你能帮我解决什么问题吗?

2 个答案:

答案 0 :(得分:0)

您必须为临时子表

添加表别名

在这种情况下,请在底部看到添加的as t

select userid, name, checktime, campaign,

CASE WHEN Hoursworked - 9 > 0 THEN Hoursworked - 9 ELSE 0 END Overtime
from
(

    select  
    a.userid,a.name,a.campaign,

    date(a.CHECKTIME),
    timediff(max(b.CHECKTIME), min(a.CHECKTIME)) as Hoursworked
    from CHECKINOUT a

    join CHECKINOUT b

    on date(a.CHECKTIME) = date(b.CHECKTIME) and a.userid = b.userid
    where
    a.CHECKTYPE = 'I'

    AND b.CHECKTYPE = 'O'

    group by date(a.CHECKTIME), userid
) as t

答案 1 :(得分:0)

您需要使用add a name for the subquery

  

子查询在SELECT语句的FROM子句中是合法的。实际上   语法是:

     

SELECT ... FROM (subquery) [AS] name ...

     

[AS] name子句是必需的,因为FROM中的每个表都是如此   子句必须有一个名字。子查询选择列表中的任何列都必须   有独特的名字。

请通过以下方式为子查询添加别名:

select userid, name, checktime, campaign,

CASE WHEN Hoursworked - 9 > 0 THEN Hoursworked - 9 ELSE 0 END Overtime
from
(

    select  
    a.userid,a.name,a.campaign,

    date(a.CHECKTIME),
    timediff(max(b.CHECKTIME), min(a.CHECKTIME)) as Hoursworked
    from ...
) AS T  --here is the alias