连接查询
SELECT SC.Sno, C.Cname, C.Grade
FROM SC, Course C
WHERE SC.Cno = C.Cno; //表外连接
SELECT A.Cno, B.Cpno
FROM Course A, Course B
WHERE A.Cpno = B.Cno; //表内连接
SELECT C.Cno, C.Cname, COUNT(SC.Sno)
FROM Course C, SC
WHERE C.Cno =* SC.Cno
GROUP BY C.Cno; //*为外连接符号,*出现在连接条件的右边称为左外连接,*出现在连接条件的左边称为右外连接
SELECT S.Sname, S.Sdept
FROM Student S, SC
WHERE S.Sno = SC.Sno AND SC.Cno = '1156' AND SC.Grade > 80; //多条件查询
SELECT S.Sno, S.Sname, C.Cname, SC.Grade
FROM Student S, SC, Course C
WHERE S.Sno = SC.Sno AND SC.Cno = C.Cno
ORDER BY S.Sno; //ORDER BY多条件查询
SQL2中的连接查询表达方法
R [NATURAL] {CROSS | LEFT OUTER | RIGHT OUTER | FULL OUTER } JOIN S {ON 条件 | USING(1, A2, …, An) }
1. 笛卡尔积
Student CROSS JOIN SC; //结果包含Student和SC中的所有属性(8个),Student中的任何一个元组和SC中任何一个元组连接一个结果元组。
2. Theta连接
Student JOIN SC ON Student.Sno = SC.Sno; //结果包含Student和SC中的所有属性(8个),Student和SC中满足条件的元组进行连接形成结果元组。
3. 自然连接
Student NATURAL JOIN SC; //结果包含Student和SC中的所有属性去掉重复的属性(7个),Student和SC中满足条件的元组进行连接形成结果元组。
4. 外连接
左外连接 | LEFT OUTER JOIN |
右外连接 | RIGHT OUTER JOIN |
全外连接(既左外连接又右外连接) | FULL OUTER JOIN |
Course RIGHT OUTER JOIN SC ON Student.Sno = SC.Sno;
SELECT Sname, Sdept FROM Student NATURAL JOIN SC WHERE Cno = ‘1156’;