4.4 多表操作
用 JOIN 把学生表、课程表、成绩表连起来,才能算出“谁选了什么课、考了多少分”。
本讲导览
核心内容
多表操作
📄 展开课件原文(第 1–1 页,共 1 页)
表的复制
1、复制一个表(结构和数据)
create table 新表 select * from 旧表;只是复制部分结构(主键和自动增长不复制)和全部数据。
2、只复制一个表的结构
create table 新表 select * from 旧表 where 1=2;只是复制部分结构(主键和自动增长不复制)
3、只复制数据(假设2个表结构一样)
假设2个表都存在,且结构一样
Insert into 目的表 select * from 源表将“源表”中的数据,插入到“目的表”中。
4、复制部分数据(假设2个表结构不一样)
假设2个表都存在,且结构不完全一样
Inset into 目的表(字段列表1) select 字段列表2 from 源表 where 条件
5、只拷贝结构
create table 新表 like 旧表;只拷贝结构,包括主键。
如果要再复制数据,可以再用命令实现
6、只复制部分字段和数据
Create table 新表 (select 字段1,字段2,… from 旧表)小结:
1、复制一个表的基本结构(不包括主键、自动增长等)和全部数据。
create table 学生表 select * from student;2、只复制一个表的基本结构(不包括主键、自动增长等),不包括数据。
Create table 学生表2 select * from student where 1=2;思考:此时,想把原表的数据,都插入到新表中,怎么做?
Insert into 学生表2 select * from student;说明:这种用法要求这2个表的结构要相同。
3、完全复制一个表的结构(包括主键、自动增长等),但不包括数据。
Create table 学生表3 like student;4、插入部分数据,来自另一个表中
语法:insert 表1(字段列表1) select 字段列表2 from 表2 where 条件;
如:insert into 学生表3(stuno,stuname) select stuno,stuname from student;说明:
(1)字段列表1和字段列表2,个数相同、类型相同或兼容,顺序一一对应。
(2)不赋值的字段,必须允许为空
📄 展开课件原文(第 2–6 页,共 5 页)
多表查询
1、从2个表中查询出数据
从多个表中查询出数据,通常用等值连接查询
等值连接:
条件中,使用“表1.字段名1=表2.字段名2”的方式。
如:select classname,stuno,stuname from class,student where class.ClassNo=student.ClassNo;
或select classname,stuno,stuname from class join student on class.ClassNo=student.ClassNo;注意:其写法不一样。
2、联合查询
从多个表中查询的结果,合并到一个结果集中。
各个表的字段列表相同或类型兼容。
select a,b from A union select c,d from B;
select classno,classname from class union select classno,stuname from student;3:带子查询的插入
向表中插入的记录可以来自另一张表, 我们可以将一个子查询的结果集插入到一个表中,语法格式如下:
INSERT INTO 表名[{字段列表}] <子查询>
说明:
其中,当表名后的{字段列表}省略时,子查询的目标列要与表中字段的数目顺序和数据类型一致;若不省略{字段列表},子查询的目标列须和{字段列表}保持一致。
格式为:
INSERT INTO 表1(字段列表1)
select 字段列表2 from 表2 where 条件。字段列表1和字段列表2的数据类型、个数要一一对应。
例1:
(1)将student表,只拷贝结构为表“学生”。
create table 学生 like student;(2)向学生表中插入数据,数据来自student表中classno为‘20000001’的同学。
insert into 学生 select * from student where classno='20000001';📄 展开课件原文(第 7–10 页,共 4 页)
课件里的提醒 课件原文中的“说明 / 注意 / 出错”
- 说明:这种用法要求这2个表的结构要相同。
- 注意:其写法不一样。
本讲 SQL 速览 把课件里出现的语句集中起来,方便照着敲
create table 新表 select * from 旧表;create table 新表 select * from 旧表 where 1=2;Insert into 目的表 select * from 源表create table 新表 like 旧表;Create table 新表 (select 字段1,字段2,… from 旧表)create table 学生表 select * from student;Create table 学生表2 select * from student where 1=2;Insert into 学生表2 select * from student;Create table 学生表3 like student;如:insert into 学生表3(stuno,stuname) select stuno,stuname from student;如:select classname,stuno,stuname from class,student where class.ClassNo=student.ClassNo;或select classname,stuno,stuname from class join student on class.ClassNo=student.ClassNo;