表的关系分为四种:
- 一对一 one to one QQ和QQ邮箱,员工和员工编号
- 一对多 one to many 最常见,部门和员工,用户和订单
- 多对一 many to one 一对多反过来,员工和部门,订单和用户
- 多对多 many to many 老师和学生,老师和课程
三种连接 join
- 内连接 inner join
- 左(外)连接 left join
- 右(外)连接 right join
单行子查询
select * from laoshi where laoshi=any(select laoshi from xuesheng where laoshi='b老师');
select * from laoshi where laoshi=any(select laoshi from xuesheng where laoshi='a老师');
多行子查询
select * from laoshi where laoshi in (select * from xuesheng where laoshi='a老师');
left join
SELECT l.laoshi,x.xingming
FROM laoshi l INNER JOIN xuesheng x
ON l.laoshi=x.laoshi
WHERE l.laoshi='a老师';
- INNER JOIN两边都对应有记录的才展示,其他去掉
- LEFT JOIN左边表中的数据都出现,右边没有数据以NULL填充
- RIGHT JOIN右边表中的数据都出现,左边没有数据以NULL填充
SQL的执行顺序
(1) FROM [left_table] 选择表
(2) ON <join_condition> 链接条件
(3) <join_type> JOIN <right_table> 链接
(4) WHERE <where_condition> 条件过滤
(5) GROUP BY <group_by_list> 分组
(6) AGG_FUNC(column or expression),... 聚合
(7) HAVING <having_condition> 分组过滤
(8) SELECT (9) DISTINCT column,... 选择字段、去重
(9) ORDER BY <order_by_list> 排序
(10) LIMIT count OFFSET count; 分页
.