连接查询

举例:

笛卡尔乘积现象:
select name,boyname from beauty,boys;

添加有效的连接条件进行避免:

连接查询的分类:

sql92标准(只支持内连接)
等值连接


为表起别名:提高简洁度,区分多个重名的字段,如果为表起了别名,则查询的字段就不能用原来的表名去限定





三表连接案例:

非等值连接

自连接,和自连接的区别是,自己和自己连接(一般是表中有特殊字段才能进行自连接)
案例:


sql99标准
语法:

92和99语法对比:

举例:

内连接:

-
等值连接:
1.
2.
3.
image.png
特点:
image.png
- 非等值连接
查询员工工资级别个数>20的个数,并且按工资级别降序
SELECT
grade_level,count(*) mount
FROM employees e
join job_grades j
on e.salary between j.lowest_sal and j.highest_sal
GROUP BY grade_level
HAVING mount>20
ORDER BY grade_level DESC
-
自连接
查询员工的上级:
表,将同一张表看作2张表,进行自连接
SELECT
e.last_name 员工名,e.employee_id 员工id,m.last_name 领导名,m.employee_id 领导id
FROM employees e
join employees m
on e.manager_id = m.employee_id

外连接
应用场景:查询一个表有而另一个表没有的数据时就需要用到外连接了。


-
左右外连接
左连接
右连接
-
全(外)连接
全连接
交叉连接

连接查询总结
1.以后推荐使用sql99语法,更有优势



网友评论