小工具知识网

当前位置: 首页 > 行业知识 > MySQL - 创建表的三种方法详解及练习

行业知识

MySQL - 创建表的三种方法详解及练习

2026-11-03 05:18:14 来源:互联网转载

目录

1. 基础创建

实例1

2. 带约束创建

实例2

3. 复制创建

 实例3:

 实例4:

 实例5:

​ 实例6:

 实例7:

4. 牛客题:


1. 基础创建

-- 基本语法CREATE TABLE 表名称(    字段名1 数据类型1,    字段名2 数据类型2,    字段名3 数据类型3);

实例1

创建一个actindex.php/tags-1038.html" >or表,包含如下列信息

列表

类型

actor_id

smallint(5)

first_name

varchar(45)

last_name

varchar(45)

last_update

date

示例代码

drop table if exists actor;create table actor(    actor_id smallint(5),    first_name varchar(45),    last_name varchar(45),    last_update date);

结果:

2. 带约束创建

-- 基本语法CREATE TABLE 表名称(    字段名1 数据类型1 主键 自增长,    字段名2 数据类型2 非空 默认值,    字段名3 数据类型3)ENGINE=当前表格的引擎 AUTO_INCREMENT=自增长的起始值 DEFAULT CHARSET=表数据的默认字符集;

实例2

创建一个actor表,包含如下列信息

CHARSET为utf8,ENGINE为INNODB

列表

类型

是否为NULL

含义

其他

actor_id

smallint(5)

not null

主键id

自增从1开始

first_name

varchar(45)

not null

名字

last_name

varchar(45)

not null

姓氏

last_update

date

not null

日期

drop table if exists actor;create table actor(    actor_id smallint(5) primary key auto_increment comment '主键id',    first_name varchar(45) not null comment '名字',    last_name varchar(45) not null comment '姓氏',    last_update date not null comment '日期')ENGINE=INNODB,AUTO_INCREMENT=1,DEFAULT charset =utf8;

 结果:

3. 复制创建

CREATE TABLE new_table LIKE old_table;   #复制表的所有结构CREATE TABLE new_table SELECT list FROM old_table WHERE 0;  #复制表的部分结构CREATE TABLE new_table SELECT * FROM old_table;   #复制表的所有结构+所有数据CREATE TABLE new_table SELECT field_list FROM old_table;  #复制表的部分结构+所有数据CREATE TABLE new_table SELECT field_list FROM old_table WHERE condition;  #复制表的部分结构+部分数据 

先往实例2创建的actor表中插入几条数据

insert into actor values ('1', 'PENELOPE', 'GUINESS', '2006-02-15 12:34:33'),                          ('2', 'NICK', 'WAHLBERG', '2006-02-15 12:34:33');

 关于如何插入数据的讲解可参选如下连接:

Mysql - 常用插入数据的三种方法详解及练习-CSDN博客

实例3:

另建一个和actor一样的空表actor_copy

drop table if exists actor_copy;create table actor_copy like actor;

 结果

 实例4:

将actor表中的first_name, last_name单独拿出来,存在一个新的空表actor_name中

create table actor_nameselect first_name,last_namefrom actorwhere 0;

 结果:

 

 实例5:

另建一个和actor一模一样表actor_copy1

create table actor_copy1select *from actor;

 结果

实例6:

请你创建一个actor_name2表,并且将actor表中的所有first_name以及last_name导入该表.

create table actor_name2select first_name,last_namefrom actor;

 结果

 实例7:

请你创建一个actor_name3表,并且将actor表中的first_name为’Nick'人的first_name和last_name导入该表.

create table actor_name3select first_name,last_namefrom actorwhere first_name='NICK';

结果:

4. 牛客题:

SQL227 创建一个actor表

SQL230 创建一个actor_name表

上一篇:SpringBoot——嵌入式 Servlet容器

下一篇:苹果手机怎么写服务器连接?