[MySQL] Several methods to quickly create new tables based on existing tables

Create the student table t_student, the syntax is:

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
);

Add some student data to the student table:

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]');

To view the student table:

select * from t_student;

 

Use the student table t_student as the object to quickly create a new database table.


Method 1: Quickly create a table: the structure and data are consistent with t_student

create table t_student2
as
select * from t_student;

View the data in the table:

select * from t_student2;

Method 2: Quickly create a table with the same structure as t_student, but without data 

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

Where is followed by the filtering condition, and only the records that meet the condition are selected, because the condition (1=2) is false, so the whole sentence is actually not selecting anything, which can be used to copy a table structure.

View the data in the table:

select * from t_student3;

Method 3: Quickly create a table: only some columns and some data :

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

View the data in the table:

select * from t_student4;

 

Guess you like

Origin blog.csdn.net/hold_on_qlc/article/details/130173661