create table as 和create table like的区别

时间:2022-02-22 00:54:50

create table as 和create table like的区别

对于MySQL的复制相同表结构方法,有create table as 和create table like 两种,区别是什么呢?

/*
-- 没有开启gtid的情况下,不拷贝数据,只创建一模一样的表结构,包括索引约束等,结合insert语句可以实现复制一个表的结构和数据的目的
create table tbl_test_bak like  tbl_test; 
insert into tbl_test_bak select * from tbl_test;

-- 以下方式也可以创建表结构,包含数据,但是没有索引约束等,所以不推荐再使用了。而且,在开启gtid情况下,会报语法错误
create table tbl_test_bak as select * from tbl_test;
*/

-- drop table if exists tbl_test ;
create table tbl_test (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  name varchar(20) NOT NULL,
  PRIMARY KEY (id),
  KEY idx_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

insert into tbl_test(name) values('aaa');
insert into tbl_test(name) values('bbb');
insert into tbl_test(name) values('AAA');
insert into tbl_test(name) values('BBB');

mysql> select * from tbl_test;
+----+------+
| id | name |
+----+------+
|  1 | aaa  |
|  3 | AAA  |
|  2 | bbb  |
|  4 | BBB  |
+----+------+
4 rows in set (0.00 sec)

mysql> create table tbl_test_bak like  tbl_test;
Query OK, 0 rows affected (0.04 sec)

mysql> select * from tbl_test_bak\G;
Empty set (0.00 sec)

ERROR: 
No query specified

mysql> create table tbl_test_bak as select * from tbl_test;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> show create table tbl_test_bak\G;
*************************** 1. row ***************************
       Table: tbl_test_bak
Create Table: CREATE TABLE `tbl_test_bak` (
  `id` bigint(20) NOT NULL DEFAULT '0',
  `name` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> select * from tbl_test_bak;
+----+------+
| id | name |
+----+------+
|  1 | aaa  |
|  3 | AAA  |
|  2 | bbb  |
|  4 | BBB  |
+----+------+
4 rows in set (0.00 sec)