mysql---連接查詢

連接查詢(多表查詢)
內(nèi)連接
外連接
---左外連接
---右外連接

前提條件:多張表之間要存在相關(guān)聯(lián)的字段


內(nèi)連接

特征:只有相關(guān)聯(lián)字段具有相同的值時(shí),才顯示對(duì)應(yīng)的結(jié)果

語(yǔ)法:

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ù),右表中沒(méi)有關(guān)聯(lián)的數(shù)據(jù)時(shí),顯示為NULL

語(yǔ)法:

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ù),左表中沒(méi)有關(guān)聯(lián)的數(shù)據(jù)時(shí),顯示為NULL

語(yǔ)法:

SELECT tb1.col, tb2.col,.... FROM tb1 RIGHT JOIN tb2 ON tb1.col=tb2.col


嵌套查詢/子查詢

以查詢的結(jié)果作為另外一個(gè)查詢的條件、數(shù)據(jù)源使用

mysql> SELECT * FROM tutors WHERE Age > (SELECT AVG(Age) FROM tutors);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容