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

Aka*_*ash 1 mysql sql

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

select (@a) 
from ( SELECT (@a :="")
             ,(select (@a) 
               from information_schema.schemata 
               where (@a) in (@a := concat(@a, schema_name, '<br>'))
               )
     ) a
Run Code Online (Sandbox Code Playgroud)

Akh*_*hil 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
Run Code Online (Sandbox Code Playgroud)

为了更清晰,请运行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;
Run Code Online (Sandbox Code Playgroud)

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

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

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