解释此SQL查询,显示使用变量的数据库列表

问题描述 投票:1回答:1

谁能解释这个SQL查询是如何工作的?我一直试图弄明白,但无法得到这个查询背后的逻辑。

select (@a) 
from ( SELECT (@a :="")
             ,(select (@a) 
               from information_schema.schemata 
               where (@a) in (@a := concat(@a, schema_name, '<br>'))
               )
     ) a
mysql sql
1个回答
6
投票
SELECT 
    @a -- Final Result (3)
        FROM 
        ( 
             SELECT (@a :="") -- Resetting the variable after each run, (1)
            (
                SELECT @a -- Does really nothing. This can be anything 
                    FROM information_schema.schemata 
                        WHERE (@a) IN (@a := CONCAT(@a, schema_name, '<br>')) -- This will be executed for each row. But none of the rows will match. At the end, @a will have the desired output  (2)
            )
    ) a

为了更加清晰,请运行SELECT * from information_schema.schemata并查看输出

(1),(2),(3)表示执行优先级

如果我们拆分查询,则会发生以下情况

 SET @a = "";

 SELECT 1 FROM information_schema.schemata WHERE (@a) IN (@a := CONCAT(@a, schema_name, '<br>'));

 SELECT @a;

编辑:问题:如果没有行匹配,变量“a”将如何具有所需的输出?

让我们采取一个小查询select * from mytable where (somecondition)如果mytable有10条记录而somecondition不使用任何索引,那么somecondition将执行10次。根据每次执行,如果结果为真/ 1,则将显示该行。这是sql select语句的简单理论。

现在你可以用somecondition替换(@a) IN (@a := CONCAT(@a, schema_name, '<br>')),你会得到答案

© www.soinside.com 2019 - 2024. All rights reserved.