错误代码1248,SQL状态42000:每个派生表必须具有自己的别名

时间:2015-04-10 16:10:38

标签: mysql sql mysql-error-1064

我在MySQL上运行此查询。

Select Vendor, sum(Rate) as Rate
from (select case Vendor when 'NSN' then 'Nokia' else Vendor end as Vendor, Rate
from (  Select vendor ,(count(1) )*100/(Select count(id_incident)from incident where open_time between '2015-01-01'and'2015-01-30') as Rate from incident  where open_time between '2015-01-01'and'2015-01-30'group by upper (vendor) )) as y group by vendor;   

并且它给出了这个错误:

  

错误代码1248,SQL状态42000:每个派生表必须有自己的别名“。

问题是什么?

2 个答案:

答案 0 :(得分:0)

您忘记给内部子查询添加别名。我选择了x

Select Vendor, sum(Rate) as Rate
from 
(
   select case Vendor when 'NSN' then 'Nokia' else Vendor end as Vendor, Rate
   from 
   (  
     Select vendor ,(count(1) )*100/(Select count(id_incident)from incident where open_time between '2015-01-01'and'2015-01-30') as Rate 
     from incident  
     where open_time between '2015-01-01'and'2015-01-30'
     group by upper (vendor) 
   ) as x
) as y 
group by vendor;   

答案 1 :(得分:0)

您的查询比以前更加复杂:

 Select (case when vendor = 'NSN' then 'NOKIA' else upper(vendor) end) as vendor,
        count(*)*100 / overall.cnt as Rate 
 from incident i cross join
      (Select count(*) as cnt
       from incident
       where open_time between '2015-01-01'and'2015-01-30'
      ) overall
 where open_time between '2015-01-01'and'2015-01-30'
 group by (case when vendor = 'NSN' then 'NOKIA' else upper(vendor) end)

评论:

  • 子查询(在MySQL中)会产生额外的开销,用于实现中间结果。
  • 每行调用一次select子句中的子查询。在from中,它只计算一次。
  • 如果id_incident不为NULL,则只需使用count(*)(或count(1))。如果您没有真正检查count()值,则在NULL中添加列会产生误导。