浅析MySQL关联left join 条件on与where的区别
以下的文章主要讲述的是MySQL关联left join 条件on与where 条件的不同之处,我们现在有两个表,即商品表(products)与sales_detail(销售记录表)。我们主要是通过这两个表来对MySQL关联left join 条件on与where 条件的不同之处进行讲述。
products:
pid pname pcode
1 商品1 AC90
2 商品2 DE78
3 商品3 XXXX
1. sales_detail:
2. aid pcode saletime
3. 1 AC90 2008-09-22
4. 2 DE78 2008-09-22
5. 3 AC90 2008-09-23
6. 4 AC90 2008-09-24
按商品在某个时间段内的销售量来排行,比如我想统计23-24号这两天的销售数量并排行。(注:DE78这个商品在这两天没有销售,但是也要显示出来,只是数量为0)。
MySQL关联left join条件on和where条件的区别表的结构 `products`
1. CREATE TABLE `products` (
2. `pid` int(3) NOT NULL auto_increment,
3. `pname` varchar(20) NOT NULL,
4. `pcode` varchar(20) NOT NULL,
5. PRIMARY KEY (`pid`)
6. ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
导出表中的数据 `products`
1. INSERT INTO `products` (`pid`, `pname`, `pcode`) VALUES (1, '商品1', 'AC90'),
2. (2, '商品2', 'DE78'),
3. (3, '商品3'. 'XXXX');
表的结构 `sales_detail`
1. CREATE TABLE `sales_detail` (
2. `aid` int(3) NOT NULL auto_increment,
3. `pcode` varchar(20) NOT NULL,
4. `saletime` date NOT NULL,
5. PRIMARY KEY (`aid`)
6. ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
导出表中的数据 `sales_detail`
1. INSERT INTO `sales_detail` (`aid`, `pcode`, `saletime`) VALUES (1, 'AC90', '2008-09-22'),
2. (2, 'DE78', '2008-09-22'),
3. (3, 'AC90', '2008-09-23'),
4. (4, 'AC90', '2008-09-24');
MySQL关联left join条件on和where条件的区别区别两条sql语句:
1. select p.pname,p.pcode,s.saletime,count(s.aid) as total from products as p
2. left join sales_detail as s on (s.pcode=p.pcode)
3. where s.saletime in ('2008-09-23','2008-09-24')
4. group by p.pcode order by total desc,p.pid asc
5. +---------+-------+------------+-------+
6. | pname | pcode | saletime | total |
7. +---------+-------+------------+-------+
8. | 商品1 | AC90 | 2008-09-23 | 2 |
9. +---------+-------+------------+-------+
10. select p.pname,p.pcode,s.saletime,count(s.aid) as total from products as p
11. left join sales_detail as s on ((s.pcode=p.pcode) and s.saletime in ('2008-09-23','2008-09-24'))
12. group by p.pcode order by total desc,p.pid asc
13. +---------+-------+------------+---------+
14. | pname | pcode | saletime | total |
15. +---------+-------+------------+-------+
16. | 商品1 | AC90 | 2008-09-23 | 2 |
17. | 商品2 | DE78 | NULL | 0 |
18. | 商品3 | XXXX | NULL | 0 |
19. +---------+-------+------------+---------+
心得:on中的条件关联,一表数据不满足条件时会显示空值。where则输出两表完全满足条件数据。
where:数据采集完后执行where
join on and:先执行and,再join