LIMIT :
1. 求TOPN
2. 查看有限条数据
3. 分页
select * from product limit 0,5;从第一条数据开始,一页显示5条数据
Limit M,N ;从M+1条开始,显示N条数据
select * from product limit 5;
--求分类里面产品个数最多的N个
select category_id ,count(1) as cn from product where price is not null group by category_id having cn >2 order by cn desc limit 1 ;
insert into ... select ....
需求: 统计每个分类的产品个数,保存在一个表里面
第一步: select category_id,count(1) as cn from product group by category_id;
第二步:建表
create table category_cn
(category_id varchar(20),
cn int
);
第三步 : 将结果数据写入表中
insert into category_cn
select category_id ,count(1) from product group by category_id;
创建临时表的方式存储数据:create table as ... select ....
create table category_cn_tmp
as
select category_id,count(1) as cn from product group by category_id;
主外键约束:当一个表的外键指向另外一个表的主键,就形成主外键关系
主表:被指向的表,category表
从表:products
主键:主表里面的主键
外键:从表里面的外键
注意:
添加数据的时候从主表开始
删除数据从从表开始
多表关联:
内连接:
隐式内连接:select * from A ,B ;
默认是将左边表的每一条数据与右边表的每一条数据进行拼接,结果是错误的。
select * from category,products where cid=category_id;拿到正确的结果
显示内连接:inner join
select * from products t1 inner join category t2 ;笛卡尔积的结果是错的
select * from products t1 inner join category t2 on t1.category_id=t2.cid;推荐
select * from products t1 inner join category t2 where t1.category_id=t2.cid;
select * from products t1 join category t2 on t1.category_id=t2.cid;
外连接:
左外连接:left join on
左边表的数据与右边的表的数据根据条件连接
1. 如果连接上就拿到
2. 如果没有连接上的也要拿到,右边表的这些数据的值为null
select * from products t1 left join category t2 on t1.category_id = t2.cid
select * from category t1 left join products t2 on t2.category_id = t1.cid;
右外连接:
右边的表与左边的表根据条件连接
1. 右边的表与左边连接上的数据都拿到
2. 右边与左边没有连接上的数据也要拿到,但是左边对应的值为null
select * from products t1 right join category t2 on t1.category_id=t2.cid