MySQL创建表的三种方式

创建表的三种方式

通过create语句直接创建

语法:

create [TEMPORARY] table [IF NOT EXISTS] table_name
(
	col_name column_defination [constrant] [NOT NULL | NULL] [DEFAULT {literal | (expr)}]  [COMMENT string]
)[table_option] ;
常见table_option:
ENGINE [=] engine_name CHARACTER SET [=] charset_name

示例:

create table if not exists test1
(
    id     int auto_increment primary key comment 主键id,
    `name` varchar(10) not null,
    sex    bit(1)      not null,
    address varchar(50) not null ,
    phone char(11) not null ,
    createTime timestamp default CURRENT_TIMESTAMP,
    updateTime timestamp default current_timestamp on update current_timestamp
)engine = Innodb CHARACTER SET utf8mb4;

通过as关键字创建

语法:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name  [AS] query_expression

示例:

create table test2 as select id,name,sex,createTime from test1;

效果展示:

总结:

通过这种方式创建的表格会把查询到的数据以及对查询表格字段的定义都会复制复制过来。

通过create…like创建

语法:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    { LIKE old_tbl_name | (LIKE old_tbl_name) }

示例:

create table test3 like test2;

总结:

通过这种方式创建的表格会把之前的表框架都复制过来,但不会复制数据。

经验分享 程序员 微信小程序 职场和发展