谁能解释这个SQL查询是如何工作的?我一直试图弄明白,但无法得到这个查询背后的逻辑。
select (@a)
from ( SELECT (@a :="")
,(select (@a)
from information_schema.schemata
where (@a) in (@a := concat(@a, schema_name, '<br>'))
)
) a
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>'))
,你会得到答案