当前位置: 代码迷 >> 综合 >> [Err] 1248 - Every derived table must have its own alias
  详细解决方案

[Err] 1248 - Every derived table must have its own alias

热度:48   发布时间:2024-01-04 02:31:27.0

 

mysql执行多表查询时报错:

select * from (
SELECT EXTRACT(YEAR FROM NOW()) YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -1 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -2 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -3 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -4 YEAR from DUAL 
)

 

[Err] 1248 - Every derived table must have its own alias


一般是在多表查询或者子查询的时候会出现这个错误,因为在嵌套查询中,子查询的结果是作为一个派生表给上一级进行查询,所以子查询的结果必须有一个别名。这句话的意思是每个派生出来的表必须有一个自己的别名

上面的例子中,把查询语句修改一下:

select * from (
SELECT EXTRACT(YEAR FROM NOW()) YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -1 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -2 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -3 YEAR from DUAL 
UNION
SELECT EXTRACT(YEAR FROM NOW()) -4 YEAR from DUAL 
) as total

如上所示,在子查询的后面增加一句 as total,相当于给子查询的结果集派生表取别名为total,问题就解决了。

  相关解决方案