MySQL:创建临时表时是否自动创建主键?

Nic*_*oll 5 mysql sql indexing temp-tables

我有一个查询需要相当长的时间(大约 1100 万个观察值)和三个连接(我无法阻止它进行检查)。其中一个连接是使用临时表。

当我使用其中包含主键的表中的数据创建临时表时,新表是否会继承索引,或者我是否必须在新临时表中显式创建索引(使用父表中的主键)桌子)?

Pau*_*gel 5

否 - 对于显式定义的临时表,不会自动定义索引。您需要在创建表时或之后使用ALTER TABLE ...

您可以使用 检查它SHOW CREATE TABLE my_temptable

尝试以下脚本:

drop table if exists my_persisted_table;
create table my_persisted_table (
    id int auto_increment primary key,
    col varchar(50)
);
insert into my_persisted_table(col) values ('a'), ('b');

drop temporary table if exists my_temptable;
create temporary table my_temptable as 
    select * from my_persisted_table;

show create table my_temptable;

alter table my_temptable add index (id);

show create table my_temptable;
Run Code Online (Sandbox Code Playgroud)

第一条SHOW CREATE语句将不显示任何索引:

CREATE TEMPORARY TABLE `my_temptable` (
  `id` int(11) NOT NULL DEFAULT '0',
  `col` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Run Code Online (Sandbox Code Playgroud)

创建索引后,ALTER TABLE我们可以通过第二条语句看到它SHOW CREATE

CREATE TEMPORARY TABLE `my_temptable` (
  `id` int(11) NOT NULL DEFAULT '0',
  `col` varchar(50) DEFAULT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Run Code Online (Sandbox Code Playgroud)

演示: http: //rextester.com/JZQCP29681