为何该SQL子查询执行失败?解析t1表不存在报错原因
第三条SQL执行失败的原因解释
可正常执行的SQL语句
select * from (select * from person) as t1; /*ok*/ select * from (select * from person) as t1 where t1.birthday >= '1987-04-09'; /*ok*/
执行报错的SQL语句
select * from (select * from person) as t1 where t1.birthday = (select max(birthday) from t1); /* fails with 't1 doesn't exist' */
正确写法
select * from person where person.birthday = (select max(birthday) from person) /*ok*/
报错原因
核心是SQL的作用域规则:
(select * from person) as t1创建的t1是临时派生表,它的可见范围仅限外层查询的FROM子句之后、同层级的直接条件中(比如第二条SQL里直接用t1.birthday过滤是合法的,属于同一查询上下文)。WHERE子句里嵌套的(select max(birthday) from t1)是独立子查询,它的作用域只能访问数据库中持久存在的表,看不到外层临时生成的t1,因此会抛出“t1 doesn't exist”的错误。- 正确写法直接引用原表
person,因为person是数据库中持久化的表,所有嵌套子查询都能正常访问,所以可以顺利执行。
内容的提问来源于stack exchange,提问作者user7657133
相关产品推荐
相关产品推荐

