今天在工作碰見關於left join 中on 與where 區別的問題,開始不知道left join 中還可以用where。問了同事才知道!在此記錄下以便以後查詢。
區別: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則輸出兩表完全滿足條件數據。