以下的文章主要讲述的是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
- sales_detail:
- aid pcode saletime
- 1 AC90 2008-09-22
- 2 DE78 2008-09-22
- 3 AC90 2008-09-23
- 4 AC90 2008-09-24
按商品在某个时间段内的销售量来排行,比如我想统计23-24号这两天的销售数量并排行。(注:DE78这个商品在这两天没有销售,但是也要显示出来,只是数量为0)。
MySQL关联left join条件on和where条件的区别表的结构 `products`
- CREATE TABLE `products` (
- `pid` int(3) NOT NULL auto_increment,
- `pname` varchar(20) NOT NULL,
- `pcode` varchar(20) NOT NULL,
- PRIMARY KEY (`pid`)
- ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
导出表中的数据 `products`
- INSERT INTO `products` (`pid`, `pname`, `pcode`) VALUES (1, '商品1', 'AC90'),
- (2, '商品2', 'DE78'),
- (3, '商品3'. 'XXXX');
表的结构 `sales_detail`
- CREATE TABLE `sales_detail` (
- `aid` int(3) NOT NULL auto_increment,
- `pcode` varchar(20) NOT NULL,
- `saletime` date NOT NULL,
- PRIMARY KEY (`aid`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
导出表中的数据 `sales_detail`
- INSERT INTO `sales_detail` (`aid`, `pcode`, `saletime`) VALUES (1, 'AC90', '2008-09-22'),
- (2, 'DE78', '2008-09-22'),
- (3, 'AC90', '2008-09-23'),
- (4, 'AC90', '2008-09-24');
MySQL关联left join条件on和where条件的区别区别两条sql语句:
- select p.pname,p.pcode,s.saletime,count(s.aid) as total from products as p
- left join sales_detail as s on (s.pcode=p.pcode)
- where s.saletime in ('2008-09-23','2008-09-24')
- group by p.pcode order by total desc,p.pid asc
- +---------+-------+------------+-------+
- | pname | pcode | saletime | total |
- +---------+-------+------------+-------+
- | 商品1 | AC90 | 2008-09-23 | 2 |
- +---------+-------+------------+-------+
- select p.pname,p.pcode,s.saletime,count(s.aid) as total from products as p
- left join sales_detail as s on ((s.pcode=p.pcode) and s.saletime in ('2008-09-23','2008-09-24'))
- group by p.pcode order by total desc,p.pid asc
- +---------+-------+------------+---------+
- | pname | pcode | saletime | total |
- +---------+-------+------------+-------+
- | 商品1 | AC90 | 2008-09-23 | 2 |
- | 商品2 | DE78 | NULL | 0 |
- | 商品3 | XXXX | NULL | 0 |
- +---------+-------+------------+---------+
心得:on中的条件关联,一表数据不满足条件时会显示空值。where则输出两表完全满足条件数据。
分享题目:MySQL关联leftjoin条件on与where不同
本文地址:http://www.shufengxianlan.com/qtweb/news30/328780.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联