在mysql查询中,有时候业务复杂了,不得不写多表查询;很多程序猿前期都喜欢写子查询,因为子查询简单易懂,不容易出问题,但子查询的效率毕竟不如关联查询;关联查询我觉得是把双刃剑,在不懂它的机制时,还是慎用,我碰到过以前的同事,因为关联查询没写好,把奖品(查询活动中奖信息)发错的,还好大奖不是汽车;
网上摘的例子,比较好理解
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则输出两表完全满足条件数据。
我的心得:where条件中的结果会影响主表的查询记录集,如果你想查询left join中主表的全部符合条件的记录,切记多看看where条件,where中的条件(不管是主表、附表的条件)会过滤掉主表中的记录集,应该放在on后面
我们知道标准查询关键字执行顺序为 from->where->group by->having->order by
left join 是在from范围类所以 先on条件筛选表,然后两表再做left join。
而对于where来说在left join结果再次筛选。
本文转载自:http://gaoerpeng777.blog.163.com/blog/static/9437945020127633739771/
时间: 2024-10-27 05:27:27