SQL 连接查询练习
时间:2021-07-01 10:21:17
帮助过:60人阅读
连接查询练习
--内连接
--返回有部门的员工工资和奖金
--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 连接查询练习
标签:语句 语法 部门 name 左外连接 工资 连接 using upper