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;

效果展示:

image-20230203194234635

总结:

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

image-20230203194519697

通过create...like创建

语法:

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

示例:

create table test3 like test2;

image-20230203194754658

总结:

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

image-20230203194932724

posted @ 2023-02-03 20:25  情韵  阅读(699)  评论(0编辑  收藏  举报