1.联表查询
1.1 表与表之间如何关联
通过主键和外键关联
主键 数据库主键是指表中一个列或列的组合,其值能唯一地标识表中的每一行。这样的一列或多列称为表的主键。当创建或更改表时可通过定义 PRIMARY KEY约束来创建主键。一个表只能有一个 PRIMARY KEY 约束,而且 PRIMARY KEY 约束中的列不能接受空值。由于 PRIMARY KEY约束确保唯一数据,所以经常用来定义标识列。
主键的特点
(1)唯一性:一个表中只能有一个主键。如果在其他字段上建立主键,则原来的主键就会取消。
(2)非空性:主键的值不可重复,也不可为空;
(3)一张表一定要有一个无意义的主键(红色 表的完整性)
主键有主键索引,会增加我们的查询速度
2 外键
如果一张表的某个列指向另一个表的主键列 ,就称之为 外键列(另一个表的主键)
1.2联表查询
为什么需要联表查询?
1.你需要的结果在一张表中无法直接获取,需要在多张表中获取到。
例子:
获取学生信息以及学生对应的班级信息。
select * from tbl_student,tbl_class;
1 李明 16 4 4 大数据01 正确
1 李明 16 4 3 软工01 错误
1 李明 16 4 2 网科01 错误
1 李明 16 4 1 计科01 错误
2 聂小倩 17 4 4 大数据01 正确
2 聂小倩 17 4 3 软工01 错误
2 聂小倩 17 4 2 网科01 错误
2 聂小倩 17 4 1 计科01 错误
3 王小明 18 1 4 大数据01 错误
3 王小明 18 1 3 软工01 错误
3 王小明 18 1 2 网科01 错误
3 王小明 18 1 1 计科01 正确
4 曹操 19 1 4 大数据01
4 曹操 19 1 3 软工01
4 曹操 19 1 2 网科01
4 曹操 19 1 1 计科01
5 宋远山 20 2 4 大数据01
5 宋远山 20 2 3 软工01
5 宋远山 20 2 2 网科01
5 宋远山 20 2 1 计科01
6 李寻欢 22 3 4 大数据01
6 李寻欢 22 3 3 软工01
6 李寻欢 22 3 2 网科01
6 李寻欢 22 3 1 计科01
---查询结果出来 但是很多数据错误。这种现象就是笛卡尔积错误。
什么是笛卡尔积?
一张表的数据 和 另一张表的每一个数组 组合了一次 这个规律我们称之为 笛卡尔乘积 问题
集合A={a, b},集合B={0, 1, 2},则两个集合的笛卡尔积为{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}。我们想用的数据:
隐士联表查询:
select * from tbl_student,tbl_class where tbl_student.cid=tbl_class.classid;
select * from tbl_student s,tbl_class c where s.cid=c.classid;
显示联表查询
-- on表示联表的条件
select * from tbl_student join tbl_class on tbl_student.cid=tbl_class.classid
select * from tbl_student s join tbl_class c on s.cid=c.classid
上面我们讲解的连接为内连接。拿到的为两种表的公共数据。

1.3左外连接
-- 左连接
select * from tbl_student s left join tbl_class c on s.classid=c.classid
-- 右连接
select * from tbl_student s right join tbl_class c on s.classid=c.classid
左 右


例:
左连接:左边表中不和右边表匹配的数据也会显示,但是所有数据会默认为null

1.4自连接

查询每个员工的姓名以及对应的领导姓名。
select e.name 员工姓名,m.name 领导姓名 from tbl_emp e left join tbl_emp m on e.mgr=m.id;
2. 嵌套查询
把一个查询的结果作为另一个查询的条件值。
例子: 查找和严丽丽薪资一样的员工信息。
select * from tbl_emp where salary=(select salary from tbl_emp where name='严丽丽')
and name!='严丽丽'
例子: 查询比计科01所有人大的学生
select * from tbl_student where age>(
select max(age) from tbl_class c join tbl_student s on c.classid=s.classid where classname='计科01');

1万+

被折叠的 条评论
为什么被折叠?



