1. 单表
1.1 排序
select * from where 条件 order by 降序列名 asc|desc;
1.2 分组
select 分组列 from 表名 group by 分组列 having 分组条件;
1.3 聚合函数
- 聚合函数:SQL基本函数,聚合函数对一组值执行计算,并返回单个值,也被称为组函数。
- 常见的聚合函数:
select count(计算个数字段) from 表名 where 条件;
select sum(求和字段) from 表名 where 条件;
select avg(求平均值字段) from 表名 where 条件;
select max(求最大值字段) from 表名 where 条件;
select min(求最小值字段) from 表名 where 条件;
- 除 COUNT 以外,聚合函数忽略空值,如果COUNT函数的应用对象是一个确定列名,并且该列存在空值,此时COUNT仍会忽略空值。
1.4 分页
select * from product limit 0,3;
select * from product limit 3,3;
select * from product limit 6,3;
select * from product limit (pageNum - 1) * pageSize, pageSize;
2.多表关系
2.1 表与表之间的关系
2.1 一对多
- 一对多关系:通过主外键关系,形成一对多关系。
- 一表 : 又称为主表,提供主键。
- 多表: 又称为从表,提供外键。
- 通过外键约束,形成外键关系。
alter table 从表 add constraint [外键名称] foreign key (外键) references 主表(主键)
2.2 多对多
- 多对多关系:提供一个中间表,将一个多对多拆分成了2个一对多。
- 练习
create table tb_order(
oid int primary key,
price double
);
create table tb_order_product(
order_id int,
product_id int
);
alter table tb_order_product add constraint foreign key (order_id) references tb_order (oid);
alter table tb_order_product add constraint foreign key (product_id) references tb_product (pid);
2.3 一对一
- 一对一关系: 同一对一多同理,通过主外键关系,形成一对一关系。