join and group

1.创建表

首先创建两个表 category(种类表),product(商品表),并向其中插入记录

create table category(
    categoryId int auto_increment,
    categoryName varchar(10) not null,
    primary key(categoryId) 
);

  

create table product(
      productId int primary key auto_increment, 
      productName varchar(10) not null,
      categoryId int,
      price int,
      constraint pro_cat foreign key (categoryId) references category(categoryId)
);

  

2.笛卡尔积

笛卡尔积其实就是将所有记录全部罗列出来,即使字段为null也会出现在查询结果中

3.内连接

内连接就是去除笛卡尔积中为null的记录

4.左外连接

查询每件商品的种类,即使商品种类为null也会出现在查询结果中,因为是左外连接,所以product中全部记录都会出现的,因此productId=4,categoryId=null这条记录不会被剔除

5.右外连接

查询product表中每件商品的种类,因为是右外连接,所以category表中所有记录都会出现,但是productId=4这条记录categoryId=null,所以结果中不会有这条记录

6.Group by

1.分组显示左外连接查询product的商品信息,但是因为lining与nike的categoryId相同,所以只显示了一个

2.继续查询,但是要显示每种categoryId对应的product数量

7.实例

1.查询每个分类中最便宜的商品的categoryId,categoryName,price

2.查询每个分类中最便宜的商品的categoryId,categoryName,productName,price,但是productName与price并没有对应......

3.我们将每类商品最小的price对应的categoryId与category.categoryId对比就可以找到与之对应的商品名称

4.这时再加一个限定条件,将price不是最小值得商品剔除

5.再进一步美化,我们只需要查询每种商品中最便宜商品的所有信息以及种类名即可

posted @ 2017-12-10 13:00  KristinLee  阅读(233)  评论(0编辑  收藏  举报
jQuery火箭图标返回顶部代码