数据库
首页 > 数据库> > MySQL:创建临时表时是否自动创建主键?

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

作者:互联网

我有一个查询,它花费了相当长的时间(大约一千一百万个观察值),并且有三个联接(我无法阻止它进行检查).联接之一是使用临时表.

当我使用其中具有主键的表中的数据创建临时表时,新表将继承索引,还是我必须在新的临时表中显式创建索引(使用父级的主键)表)?

解决方法:

否-对于显式定义的临时表,不会自动定义索引.您将需要在创建表时定义索引,或者之后使用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;

第一个SHOW CREATE语句将不显示索引:

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

在使用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

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

标签:indexing,temp-tables,sql,mysql
来源: https://codeday.me/bug/20191109/2011575.html