赞
踩
目录
多表查询
项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:
- 一对多(多对一)
- 多对多
- 一对一
就如上篇中所示的约束的例子。
建表演示多对多的关系
- create table student(
- id int auto_increment primary key comment '主键ID',
- name varchar(10) comment '姓名',
- no varchar(10) comment '学号'
- )comment '学生表';
- insert into student (name,no)
- values ('黛绮丝','2000100101'),('谢逊','2000100102'),('殷天正','2000100103'),('韦一笑','2000100104');
-
- create table course(
- id int auto_increment primary key comment '主键ID',
- name varchar(10) comment '课程名称'
- )comment '课程表';
- insert into course (name)
- values ('Java'),('PHP'),('MySQL'),('Hadoop');
-
- create table student_course(
- id int auto_increment primary key comment '主键',
- studentid int not null comment '学生ID',
- courseid int not null comment '课程ID',
- constraint fk_courseid foreign key (courseid) references course (id),
- constraint fk_student foreign key (studentid) references student (id)
- )comment '学生课程中间表';
- insert into student_course (studentid, courseid)
- values (1,1),(1,2),(1,3),(2,2),(2,3),(3,4);

接下来就可以看表与表的关系了:
- create table tb_user(
- id int auto_increment primary key comment '主键ID',
- name varchar(10) comment '姓名',
- age int comment '年龄',
- gender char(1) comment '1:男,2:女',
- phone char(11) comment '手机号'
- )comment '用户基本信息表';
-
- create table tb_user_edu(
- id int auto_increment primary key comment '主键ID',
- degree varchar(20) comment'学历',
- major varchar(50) comment '专业',
- primaryschool varchar(50) comment '小学',
- middleschool varchar(50) comment '中学',
- university varchar(50) comment '大学',
- userid int unique comment '用户ID',
- constraint fk_userid foreign key (userid) references tb_user (id)
- )comment '用户教育信息表';
-
- insert into tb_user(id, name, age, gender, phone)
- values (null, '黄渤' ,45, '1', '1800001111'),
- (null, '冰冰' ,35, '2' , '1800002222'),
- (null, '码云',55, '1', '1800008888'),
- (null, '李彦宏' ,50, '1', '1800009999');
-
- insert into tb_user_edu (id, degree, major, primaryschool, middleschool, university, userid)
- values (null,'本科','舞蹈','静安区第一小学', '静安区第-中学', '北京舞蹈学院',1),
- (null, '硕士','表演','朝阳区第小学','朝阳区第一中学', '北京电影学院' ,2),
- (null,'本科','英语','杭州市第小学','杭州市第一中学','杭州师范大学',3),
- (null, '本科','应用数学','阳泉第一小学','阳泉区第一中学','清华大学',4);

指从多张表中查询数据。
比如要查询这两张表:
一开始,我们可以使用这样的语句:
select * from emp,dept;
然后发现,查询到的结果是25条数据
很显然,这并不是我们想要的结果。出现这种情况是因为这样进行多表查询会存在无效的笛卡尔积,我们要消除无效的笛卡尔积。
笛卡尔积是指在数学中,两个集合A和集合B的所有的组合情况。
例如A、B 和1、2、3、4组合,不同的组合情况就有八种:
所以,在多表查询时,需要消除无效的笛卡尔积。
select * from emp,dept where emp.dept_id = dept.id;
就可以查到我们想要的结果啦
1.连接查询
左外连接:查询左表所有数据,以及两张表交集部分数据
右外连接:查询右表所有数据,以及两张表交集部分数据
2.子查询
在概述中仅作简单了解
end
学习自:黑马程序员——MySQL数据库课程
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。