關於left join on 和where條件放置的相關講解

來源:互聯網
上載者:User
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中文網即可觀看。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.