分组
- group by 可以认为是把一张表中的数据,按照分组字段的值,划分成了多个不同的子表
以此为例
- 对于下表 我们可以对cno字段分组统计
select cno,count(*) from 表名 group by cno;
原表
根据cno字段的值分组拆分成以下四个子表格
使用count(*) 对每个子表的数据进行统计,
关键字
group by
格式
select * from 表名 group by 分组字段 having 过滤条件
嵌套查询
当嵌套字句只有一个值
格式
select * from 表名 where 字段名 = (select 展示字段名1 from 表名)
当嵌套字句有多个值
格式
select * from 表名 where 字段名 in (select 展示字段名1from 表名)
多表关联
起别名
可以通过画ER图,更简单的明确每个表之间的联系
关联方法
- where
- join
区别
where :
第一步:拿两表数据做笛卡尔乘积生成一张中间表
第二步:根据where的条件进行筛选
- 缺点:若两表数据比较庞大的时候,生成的中间表数据量太大,会影响数据库的性能
- 以上图为例,连接上面两张表:
select * from teacher a, student b where a.sid = b.sid;
join :
第一步:先用 on+条件进行数据筛选
第二步:满足条件的显示,不满足条件的丢弃
内连接:
- 先使用on条件过滤,只显示满足条件的数据,不满足条件的跳过
- 关键字:…inner join…on… 或者…join…on…
- 格式:
select * from 表1 join 表2 on 连接条件
或者
select * from 表1 inner join 表2 on 连接条件 - 例子:
select * from teacher a join student b on a.tid = b.tid;
或者
select * from teacher a inner join student b on a.tid = b.tid;
左连接:
- 以left join 左边的表为主表,左表数据全显示,右表的数据只显示满足条件的,不满足条件的则以null代替
- 关键字:…left join…on…
- 格式:
select * from 表1 left join 表2 on 连接条件 - 例子:
select * from teacher a left join student b on a.tid = b.tid;
右连接:
- 以right join 右边的表为主表,右边的数据全部显示,左边的数据只显示满足条件的,不满足条件的则以null代替
- 关键字:…right join…on…
- 格式:
select * from 表1 right join 表2 on 连接条件 - 例子:
select * from teacher a right join student b on a.tid = b.tid;
全连接:
- 两张表都为主表,不满足条件的以null代替
- 关键字:…full join …on…
- 格式:
select * from 表1 full join 表2 on 连接条件 - 例子:
select * from teacher a full join student b on a.tid = b.tid
- 内连接,左连接,右连接,全连接 示例图对比