1. 程式人生 > >SQL 連接查詢練習

SQL 連接查詢練習

sin join 表連接 sele 語句 練習 style using 連接

                                          --連接查詢練習
                                          --內連接
--返回有部門的員工工資和獎金
--92 語法
SELECT  n.ename, n.sal, n.comm, d.deptno, d.dname
FROM new_emp n, dept d
WHERE n.deptno = d.deptno;
--99 語法
SELECT  n.ename, n.sal, n.comm, d.deptno, d.dname
FROM new_emp n INNER
JOIN dept d --可以省略 INNER ON n.deptno = d.deptno; --或使用 JOIN...USING() 語句 SELECT n.ename, n.sal, n.comm, deptno, d.dname FROM new_emp n JOIN dept d USING(deptno); -------------------------------------------------------------------------------------------------------- --
外連接(兩表連接) --叉集(笛卡爾集) SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM new_emp n CROSS JOIN dept d; --沒有部門的員工也返回(主表為員工表) --92 語法 SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM new_emp n, dept d WHERE n.deptno = d.deptno(+); --99 語法(右外連接) SELECT n.ename, n.sal, n.comm, d.deptno, d.dname
FROM dept d RIGHT OUTER JOIN new_emp n ON n.deptno = d.deptno; --沒有員工的部門也返回(主表為部門表) --92 語法 SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM new_emp n, dept d WHERE n.deptno(+) = d.deptno; --99 語法 (左外連接) SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM dept d LEFT JOIN new_emp n --可以省略OUTER ON n.deptno = d.deptno; --既返回無部門的員工股,也返回無員工的部門 --92 語法不能兩邊都寫 (+) SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM new_emp n, dept d WHERE n.deptno(+) = d.deptno(+); --該行報錯 --99 語法(滿外連接) SELECT n.ename, n.sal, n.comm, d.deptno, d.dname FROM dept d FULL OUTER JOIN new_emp n ON n.deptno = d.deptno; --------------------------------------------------------------------------------------------------------- --外連接(三表連接) --查詢所有借書記錄(不存在的學生和不存在的書均顯示) SELECT r.borrow_id, t.stu_id, t.stu_name, b.book_id, UPPER(b.book_name) FROM student t, book b, borrow r WHERE r.stu_id = t.stu_id(+) AND r.book_id = b.book_id(+) ORDER BY r.borrow_id; --只顯示不存在的書 SELECT r.borrow_id, t.stu_id, t.stu_name, b.book_id, UPPER(b.book_name) FROM student t, book b, borrow r WHERE r.stu_id = t.stu_id AND r.book_id = b.book_id(+) ORDER BY r.borrow_id; --只顯示不存在的學生 SELECT r.borrow_id, t.stu_id, t.stu_name, b.book_id, UPPER(b.book_name) FROM student t, book b, borrow r WHERE r.stu_id = t.stu_id(+) AND r.book_id = b.book_id ORDER BY r.borrow_id; --書和學生必須都存在 SELECT r.borrow_id, t.stu_id, t.stu_name, b.book_id, UPPER(b.book_name) FROM student t, book b, borrow r WHERE r.stu_id = t.stu_id AND r.book_id = b.book_id ORDER BY r.borrow_id;

SQL 連接查詢練習