首页 > 解决方案 > SQL,select语句如何在相关子查询中运行

问题描述

我试图理解以下代码。我认为第一个子查询将创建一个包含 2、3、4、5、6 的表。对于第二个子查询,我认为它将按如下方式运行。例如,@divisor 的初始值为 1,对于 nn=2,@num2<=nn 的条件有效,则执行 select 语句,则 @divisor 为 2。由于 where 条件仍然有效,再次运行select语句,使@divisor的值为3。此时where条件无效,select语句将停止。

基于这样的理解,我认为代码的结果应该是2,3,4,5,6,@divisor的最终值为6。但是,当我在mysql中运行代码时,结果为null。没有记录。

有人可以帮我吗?非常感谢。

set @num:=2;
set @num2:=1;

select nn from
    (select @num:=@num+1 as nn from 
    information_schema.tables t1, information_schema.tables t2
    where @num<=5) a
where nn in
    (select @num2:=@num2+1 from
    information_schema.tables t3, information_schema.tables t4
    where @num2<=nn)

标签: mysqlsqlsubquerymysql-dependent-subquery

解决方案


推荐阅读