MySQL:如何创建一个相同的表


#MySQL 笔记


比如,当前有一个表 test_table,需要建 test_table_1 表,表字段、索引信息等要求一样,该如何创建呢?

假设 test_table DDL 如下:

create table `test_table` (
    `id` bigint unsigned not null auto_increment,
    `name` varchar(45) not null default '',
    primary key (`id`)
) engine = InnoDB default charset = utf8mb4;

方式1:用相同的 DDL

先使用 show create table 查询表的创建语句:

mysql> show create table test_table;
***************************[ 1. row ]***************************
Table        | test_table
Create Table | CREATE TABLE `test_table` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

复制粘贴,改下表名:

create table `test_table_1` (
    `id` bigint unsigned not null auto_increment,
    `name` varchar(45) not null default '',
    primary key (`id`)
) engine = InnoDB default charset = utf8mb4;

然后执行。

方式2:使用 like

CREATE TABLE `test_table_1` like `test_table`;

方式3:使用 create ... as select .. (不建议)

CREATE TABLE `test_table_1` AS SELECT * FROM `test_table` LIMIT 0;

不建议该方式,因为最终创建的表与原表相比会少了主键、索引、表字符集等信息。

***************************[ 1. row ]***************************
Table        | test_table_1
Create Table | CREATE TABLE `test_table_1` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `name` varchar(45) CHARACTER SET utf8mb4 NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=latin1


( 本文完 )