先建立2個表:學生表和教師表mysql
在每一個表中找出符合條件的共有記錄。[x inner join y on...]
第一種寫法:只用where SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t,student s WHERE t.ID=s.TEACHER_ID
第二種寫法:使用 join..on.. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t JOIN student s ON t.ID=s.TEACHER_ID
第三種寫法:使用inner join .. on.. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t INNER JOIN student s ON t.ID=s.TEACHER_ID
(1)左鏈接:根據左表的記錄,在被鏈接的右表中找出符合條件的記錄與之匹配,若是找不到與左表匹配的,用null表示 [x left [outer] join y on...]sql
第一種寫法:left join .. on .. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t LEFT JOIN student s ON t.ID=s.TEACHER_ID
第二種寫法:left outer join .. on .. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t LEFT OUTER JOIN student s ON t.ID=s.TEACHER_ID
(2)右鏈接:根據右表的記錄,在被鏈接的左表中找出符合條件的記錄與之匹配,若是找不到匹配的,用null填充 [x right [outer] join y on...]數據庫
第一種寫法:right join .. on .. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t RIGHT JOIN student s ON t.ID=s.TEACHER_ID
第二種寫法:right outer join .. on .. SELECT t.TEACHER_NAME,s.STUDENT_NAME FROM teacher t RIGHT OUTER JOIN student s ON t.ID=s.TEACHER_ID
(3)全鏈接:返回符合條件的全部表的記錄,沒有與之匹配的,用null表示(結果是左鏈接和右鏈接的並集)spa
第一種寫法:(full join .. on ..) select t.teacher_name, s.student_name from teacher t full join student s on t.id = s.teacher_id;
第二種寫法:(full outer join .. on) select t.teacher_name, s.student_name from teacher t full outer join student s on t.id = s.teacher_id;
注意:Oracle數據庫支持full join,mysql是不支持full join的.net
若是直接查詢2張表,將獲得一個笛卡爾積,兩個表的乘積 select * from teacher,student;code
關於笛卡爾積的說明,請參考博客:http://www.javashuo.com/article/p-dragscqr-dq.html
blog