連接查詢(多表查詢)
內(nèi)連接
外連接
---左外連接
---右外連接
前提條件:多張表之間要存在相關(guān)聯(lián)的字段
內(nèi)連接
特征:只有相關(guān)聯(lián)字段具有相同的值時葬荷,才顯示對應(yīng)的結(jié)果
語法:
SELECT tb1.col, tb2.col,.... FROM tb1 INNER JOIN tb2 ON tb1.col=tb2.col
mysql> SELECT students.Name, students.Age, students.Gender, courses.Cname
-> FROM students INNER JOIN courses
-> ON students.CID1=courses.CID;
mysql> SELECT students.Name, students.Age, students.Gender, tutors.Tname
-> FROM students INNER JOIN tutors
-> ON students.TID=tutors.TID;
mysql> SELECT students.Name, students.Age, students.Gender, courses.Cname, tutors.Tname
-> FROM students INNER JOIN courses INNER JOIN tutors
-> ON students.CID1=courses.CID AND courses.TID=tutors.TID;
自然連接
mysql> SELECT students.Name, students.Age, students.Gender, courses.Cname
-> FROM students,courses
-> WHERE students.CID1=courses.CID;
外連接
左外連接
特征:以左表為主暇韧,顯示左表所有數(shù)據(jù)瘩欺,右表中沒有關(guān)聯(lián)的數(shù)據(jù)時,顯示為NULL
語法:
SELECT tb1.col, tb2.col,.... FROM tb1 LEFT JOIN tb2 ON tb1.col=tb2.col
mysql> SELECT students.Name, students.Age, students.Gender, courses.Cname
-> FROM students LEFT JOIN courses
-> ON students.CID2=courses.CID;
右外連接
特征:以右表為主鄙皇,顯示右表所有數(shù)據(jù),左表中沒有關(guān)聯(lián)的數(shù)據(jù)時,顯示為NULL
語法:
SELECT tb1.col, tb2.col,.... FROM tb1 RIGHT JOIN tb2 ON tb1.col=tb2.col
嵌套查詢/子查詢
以查詢的結(jié)果作為另外一個查詢的條件杆故、數(shù)據(jù)源使用
mysql> SELECT * FROM tutors WHERE Age > (SELECT AVG(Age) FROM tutors);