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

MySQL: Is a primary key created automatically when creating a temporary table?

我有一个查询需要很长时间(大约 1100 万次观察)和三个连接(我无法阻止它进行检查)。其中一个连接是临时 table.

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

TEMPORARY tables 与数据库(架构)的关系非常松散。删除数据库不会自动删除在该数据库中创建的任何临时 table。此外,如果在 CREATE TABLE 语句中使用数据库名称限定 table 名称,则可以在不存在的数据库中创建 TEMPORARY table。在这种情况下,对 table 的所有后续引用都必须使用数据库名称进行限定。

during generation of TEMPORARY table you have to mention all record of the table

https://dev.mysql.com/doc/refman/5.7/en/create-temporary-table.html

否 - 对于显式定义的临时 tables 没有自动定义索引。您将需要在 table 创建时或之后使用 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

此语法也适用:

create temporary table my_temptable
    ( PRIMARY KEY(id) )
    select * from my_persisted_table;

也就是说,您可以从一开始就有额外的 CREATE TABLE 子句。如果 SELECT 以 PK 顺序将行传送到 InnoDB table,这会特别有效:

create temporary table my_temptable
    ( PRIMARY KEY(id) )
        ENGINE=InnoDB
    select * from my_persisted_table
        ORDER BY id;