mysql關聯查詢和聯合查詢


一、內聯方式

   1.傳統關聯查詢

     "select * from students,transcript where students.sid=transcript.sid and transcript.total>600 and transcript.date=2015-6";

     上面是查詢出在2015-6月,月考中總成績超過600的學生信息。where的條件有三個,要看出是哪些是關聯條件,哪些是查詢過濾還是挺簡單,若是多個表多個查詢條件那么就不是那么容易了

   2.JOIN...ON

      "select * from students JOIN transcript ON(students.sid=transcript.sid) where transcript.total>600 and transcript.date=2015-6";

     這樣能很容易看出ON后面括號即關聯條件,where之后為過濾條件一目了然。語法中ON后的()不是必須的,但是為了代碼風格建議添加。

 3.JOIN...USING

   "select * from students JOIN transcript USING(sid) where transcript.total>600 and transcript.date=2015-6";

    這個時候括號就是必須的了。這種寫法很好,輸入更少的單詞,查詢性能上沒有太大的差異,但是JOIN...ON和傳統關聯查詢查詢時sid會出現二次。

 4.LEFT OUTER JOIN...ON

  "select * from students LEFT OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  選擇表students所有數據,並將transcript的數據加到students表中,若transcript中不符合條件,就不用加入結果表中,並且NULL表示

 5.RIGHT OUTER JOIN...ON

  "select * from students RIGHT OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  選擇表transcript所有數據,並將students的數據加到students表中,若students中不符合條件,就不用加入結果表中,並且NULL表示

 6.FULL OUTER JOIN...ON

  "select * from students FULL OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  選擇表student、transcript所有數據,若students,students中不符合條件,就不用加入結果表中,並且NULL表示


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM