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
)
|
一般是在多表查询或者子查询的时候会出现这个错误,因为在嵌套查询中,子查询的结果是作为一个派生表给上一级进行查询,所以子查询的结果必须有一个别名。这句话的意思是每个派生出来的表必须有一个自己的别名
上面的例子中,把查询语句修改一下:
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,问题就解决了。