我怎么知道 MySQL 中的 `auto_key0` 索引后面是什么?
How do I know what's behind the `auto_key0` index in MySQL?
说我有这个查询:
EXPLAIN SELECT *
FROM (
SELECT "A" as a, i.n FROM (SELECT 1 AS n) AS i
UNION ALL SELECT "B" as a, i.n FROM (SELECT 1 AS n) AS i) AS t
WHERE a = "B";
MySQL 说
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 PRIMARY <derived2> \N ref <auto_key0> <auto_key0> 6 const 1 100.00 \N
2 DERIVED <derived3> \N system \N \N \N \N 1 100.00 \N
3 DERIVED \N \N \N \N \N \N \N \N \N No tables used
4 UNION <derived5> \N system \N \N \N \N 1 100.00 \N
5 DERIVED \N \N \N \N \N \N \N \N \N No tables used
所以MySQL生成了一个中间索引<auto_key0>
但是这个索引背后是什么?其中使用了哪些列?有没有办法我可以手动设置这个索引,并强制 MySQL 使用一些列。
https://dev.mysql.com/doc/refman/8.0/en/derived-table-optimization.html 说:
SELECT *
FROM t1 JOIN (SELECT DISTINCT f1 FROM t2) AS derived_t2
ON t1.f1=derived_t2.f1;
The optimizer constructs an index over column f1 from derived_t2 if
doing so would enable use of ref access for the lowest cost execution
plan.
我的意思是索引的列是由连接表达式决定的。 MySQL 优化器知道哪些列对索引有用,因为它们在连接的 ON
子句中被引用。
我不知道有什么方法可以控制为派生 table 生成的索引。该指数是短暂的。它是在查询时为temptable创建的,在查询结束时temptable被删除时它会自然删除。
如果您想更好地控制索引,您必须创建自己的 table(临时或永久)并为其定义索引。
您可能还想阅读这篇关于 MySQL 优化负责人撰写的主题的博客:https://mysqlserverteam.com/mysql-5-7-improved-performance-of-queries-with-derived-tables/
EXPLAIN FORMAT=JSON SELECT ...
会 return 类似
key: <auto_key0>, used_key_parts: ['a'], key_length: 6, ref: ['const']
<auto_key0>
是优化器为派生的 table.
生成的索引
(还有 "Optimizer trace";但可能没有此特定信息。)
说我有这个查询:
EXPLAIN SELECT *
FROM (
SELECT "A" as a, i.n FROM (SELECT 1 AS n) AS i
UNION ALL SELECT "B" as a, i.n FROM (SELECT 1 AS n) AS i) AS t
WHERE a = "B";
MySQL 说
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 PRIMARY <derived2> \N ref <auto_key0> <auto_key0> 6 const 1 100.00 \N
2 DERIVED <derived3> \N system \N \N \N \N 1 100.00 \N
3 DERIVED \N \N \N \N \N \N \N \N \N No tables used
4 UNION <derived5> \N system \N \N \N \N 1 100.00 \N
5 DERIVED \N \N \N \N \N \N \N \N \N No tables used
所以MySQL生成了一个中间索引<auto_key0>
但是这个索引背后是什么?其中使用了哪些列?有没有办法我可以手动设置这个索引,并强制 MySQL 使用一些列。
https://dev.mysql.com/doc/refman/8.0/en/derived-table-optimization.html 说:
SELECT * FROM t1 JOIN (SELECT DISTINCT f1 FROM t2) AS derived_t2 ON t1.f1=derived_t2.f1;
The optimizer constructs an index over column f1 from derived_t2 if doing so would enable use of ref access for the lowest cost execution plan.
我的意思是索引的列是由连接表达式决定的。 MySQL 优化器知道哪些列对索引有用,因为它们在连接的 ON
子句中被引用。
我不知道有什么方法可以控制为派生 table 生成的索引。该指数是短暂的。它是在查询时为temptable创建的,在查询结束时temptable被删除时它会自然删除。
如果您想更好地控制索引,您必须创建自己的 table(临时或永久)并为其定义索引。
您可能还想阅读这篇关于 MySQL 优化负责人撰写的主题的博客:https://mysqlserverteam.com/mysql-5-7-improved-performance-of-queries-with-derived-tables/
EXPLAIN FORMAT=JSON SELECT ...
会 return 类似
key: <auto_key0>, used_key_parts: ['a'], key_length: 6, ref: ['const']
<auto_key0>
是优化器为派生的 table.
(还有 "Optimizer trace";但可能没有此特定信息。)