mysql 创建表 like_create table select 和 create table like 比较

create table select 语法:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name

[(create_definition,...)]

[table_options] [select_statement]

create table like 语法:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name

[(] LIKE old_tbl_name [)];

测试过程:

原数据表:mysql> show create table test_order \G

*************************** 1. row ***************************

Table: test_order

Create Table: CREATE TABLE `test_order` (

`pay_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

`origin` int(10) DEFAULT NULL,

`team_id` int(11) DEFAULT NULL,

`state` int(11) DEFAULT NULL,

KEY `team_id` (`team_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)

create table select 和 create table like 建表:mysql> create table cc select * from test_order;

Query OK, 9900 rows affected (0.11 sec)

Records: 9900  Duplicates: 0  Warnings: 0

mysql> create table dd like test_order;

Query OK, 0 rows affected (0.22 sec)

create table select 和 create table like 对比

1、数据对比:mysql> select * from cc limit 2;

+---------------------+--------+---------+-------+

| pay_time            | origin | team_id | state |

+---------------------+--------+---------+-------+

| 2011-06-22 18:04:47 |     10 |     100 |   100 |

| 2011-06-22 18:04:47 |     10 |     100 |   101 |

+---------------------+--------+---------+-------+

2 rows in set (0.00 sec)

mysql> select * from dd;

Empty set (0.00 sec)

结果:cc表中数据与原表test_order中的一致,dd表中无数据

2、表结构对比mysql> show create table cc \G

*************************** 1. row ***************************

Table: cc

Create Table: CREATE TABLE `cc` (

`pay_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

`origin` int(10) DEFAULT NULL,

`team_id` int(11) DEFAULT NULL,

`state` int(11) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)

mysql> show create table dd \G

*************************** 1. row ***************************

Table: dd

Create Table: CREATE TABLE `dd` (

`pay_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

`origin` int(10) DEFAULT NULL,

`team_id` int(11) DEFAULT NULL,

`state` int(11) DEFAULT NULL,

KEY `team_id` (`team_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)

结果:cc表中,原表中的索引消失了;dd表与原表一致

3、结论

create table select:会将原表中的数据完整复制一份,但表结构中的索引会丢失。

create table like:只会完整复制原表的建表语句,但不会复制数据

4、拓展

如果想要即能把数据完整拷贝的新表,又要有索引呢?

解决方法可以结合insert into select 语法来使用,示例如下,create table encyclopedia_of_enquiry like cooperation.encyclopedia_of_enquiry;

insert into encyclopedia_of_enquiry select * from cooperation.encyclopedia_of_enquiry;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值