连接查询(多表查询)
内连接
外连接
---左外连接
---右外连接
前提条件:多张表之间要存在相关联的字段
内连接
特征:只有相关联字段具有相同的值时,才显示对应的结果
语法:
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;
外连接
左外连接
特征:以左表为主,显示左表所有数据,右表中没有关联的数据时,显示为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;
右外连接
特征:以右表为主,显示右表所有数据,左表中没有关联的数据时,显示为NULL
语法:
SELECT tb1.col, tb2.col,.... FROM tb1 RIGHT JOIN tb2 ON tb1.col=tb2.col
嵌套查询/子查询
以查询的结果作为另外一个查询的条件、数据源使用
mysql> SELECT * FROM tutors WHERE Age > (SELECT AVG(Age) FROM tutors);