【MySQL】根据现有的表快速创建新表的几种方法

创建学生表t_student,语法为:

create table t_student(
        sno int(6) primary key auto_increment, 
        sname varchar(5) not null, 
        sex char(1) default '男' check(sex='男' || sex='女'),
        age int(3) check(age>=18 and age<=50),
        enterdate date,
        classname varchar(10),
        email varchar(15) unique
);

为学生表添加一些学生数据:

insert into t_student values (null,'张三','男',21,'2023-9-1','java01班','[email protected]');
insert into t_student values (null,'李四','男',21,'2023-9-1','java01班','[email protected]');
insert into t_student values (null,'露露','男',21,'2023-9-1','java01班','[email protected]');

查看学生表:

select * from t_student;

 

以学生表t_student为对象,快速创建新的数据库表。


方法一:快速创建一张表:结构和数据跟t_student 都是一致的

create table t_student2
as
select * from t_student;

查看表中数据:

select * from t_student2;

方法二:快速创建一张表,结构跟t_student一致,但是没有数据 

create table t_student3
as
select * from t_student where 1=2;

where 后面表示过滤的条件,只有满足条件的记录才被选择,因为条件(1=2)为假,所以整句话其实就是什么都不选择,可以用于实现拷贝一个表结构。

查看表中数据:

select * from t_student3;

方法三:快速创建一张表:只要部分列,部分数据

create table t_student4
as
select sno,sname,age from t_student where sno = 2;

查看表中数据:

select * from t_student4;

 

猜你喜欢

转载自blog.csdn.net/hold_on_qlc/article/details/130173661