当前位置:   article > 正文

MySQL创建表的三种方式

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] ;
  • 1
  • 2
  • 3
  • 4
常见table_option:
ENGINE [=] engine_name CHARACTER SET [=] charset_name
  • 1
  • 2

示例:

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
通过as关键字创建

语法:

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

示例:

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

效果展示:

image-20230203194234635

总结:

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

image-20230203194519697

通过create…like创建

语法:

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

示例:

create table test3 like test2;
  • 1

image-20230203194754658

总结:

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

image-20230203194932724

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/467303?site
推荐阅读
相关标签
  

闽ICP备14008679号