left join on 和where條件的放置問題在php中很重要,本篇會詳解其相關知識。
left join裡面帶and的查詢
SELECT p.pname,p.pcode,s.saletime from product as p left join sales_detail as s on (s.pcode=p.pcode) and s.saletime in ('2012-07-23','2012-07-05');
查出來的結果:
+-------+-------+------------+
| pname | pcode | saletime |
+-------+-------+------------+
| A | AC | 2012-07-23 |
| A | AC | 2012-07-05 |
| A | AC | 2012-07-05 |
| B | DE | NULL |
| C | XXX | NULL |
+-------+-------+------------+
直接where條件查詢
SELECT p.pname,p.pcode,s.saletime from product as p left join sales_detail as s on (s.pcode=p.pcode) where s.saletime in ('2012-07-23','2012-07-05');
查詢出來的結果
+-------+-------+------------+
| pname | pcode | saletime |
+-------+-------+------------+
| A | AC | 2012-07-23 |
| A | AC | 2012-07-05 |
| A | AC | 2012-07-05 |
+-------+-------+------------+
結論:on中的條件關聯,一表資料不滿足條件時會顯示空值。where則輸出兩表完全滿足條件資料
left join裡面的條件:會以左表的基準資料,凡左表出現的資料均要出現,然後再進行join右表,只要關聯上的就需要查出來,如果相應的欄位沒有值或不合格話就置為NULL。
SELECT p.pname,p.pcode,s.saletime from product as p left join sales_detail as s on (s.pcode=p.pcode) ;光左串連的話顯示的內容如下
+-------+-------+------------+
| pname | pcode | saletime |
+-------+-------+------------+
| A | AC | 2012-07-23 |
| A | AC | 2012-07-05 |
| A | AC | 2012-07-05 |
| B | DE | 2012-07-16 | 這裡面有值
| C | XXX | NULL | 這裡面沒有值
+-------+-------+------------+
有值但是不合格話就置為NULL。如果沒有值肯定為NULL
如果是where條件的話就肯定是要滿足才行。
應用情境:比如有個主表,那以主表為基準去顯示資料可以考慮left join的方式處理
總結:
1. 對於left join,不管on後面跟什麼條件,左表的資料全部查出來,因此要想過濾需把條件放到where後面
2. 對於inner join,滿足on後面的條件表的資料才能查出,可以起到過濾作用。也可以把條件放到where後面。
SQL中on條件與where條件的區別
資料庫在通過串連兩張或多張表來返回記錄時,都會產生一張中間的暫存資料表,然後再將這張暫存資料表返回給使用者。
在使用left jion時,on和where條件的區別如下:
1、 on條件是在產生暫存資料表時使用的條件,它不管on中的條件是否為真,都會返回左邊表中的記錄。
2、where條件是在暫存資料表產生好後,再對暫存資料表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不為真的就全部過濾掉。
本篇對left join 和where條件的放置相關的知識做出了講解,更多的學習資料清關注php中文網即可觀看。