含义:

又称多表查询,当查询的字段来自于多个表时,就会用到连接查询
笛卡尔乘积现象:表1 有m行,表2有n行,结果=m*n行
发生原因:没有有效的连接条件
如何避免:添加有效的连接条件

分类:

  1. 按年代分类:<br /> sql92标准:仅仅支持内连接<br /> sql99标准【推荐】:支持内连接+外连接(左外和右外)+交叉连接

按功能分类:

内连接:

        等值连接<br />            非等值连接<br />            自连接

外连接:

        左外连接<br />            右外连接<br />            全外连接<br />        交叉连接
SELECT * FROM beauty;
SELECT * FROM boys;
SELECT NAME,boyName FROM boys,beauty WHERE beauty.boyfriend_id= boys.id;

一、sql92标准

1、等值连接

① 多表等值连接的结果为多表的交集部分
②n表连接,至少需要n-1个连接条件
③ 多表的顺序没有要求
④一般需要为表起别名
⑤可以搭配前面介绍的所有子句使用,比如排序、分组、筛选

1:查询女神名和对应的男神名

select name,boyName from boys,beauty where beauty.boyfriend_id=boys.id;

2:查询员工名和对应的部门名

select last_name,department_name from employees,departments where employees.department_id=departments.department_id

2、为表起别名

①提高语句的简洁度
②区分多个重名的字段
注意:如果为表起了别名,则查询的字段就不能使用原来的表名去
查询员工名、工种号、工种名

select e.last_name,e.job_id,j.job_title from employees e,jobs j where e.job_id=j.job_id;

3、两个表的顺序是否可以调换

查询员工名、工种号、工种名

select e.last_name,e.job_id,j.job_title from jobs j,employees e where e.job_id=j.job_i

4、可以加筛选

查询有奖金的员工名、部门名

select last_name,department_name,commission_pct from employees e,departments d where e.department_id=d.department_id and e.commission_pct is not null;

2:查询城市名中第二个字符为o的部门名和城市名

select department_name,city from departments d,locations l where d.location_id=l.location_id
and city like '_o%';

5、可以加分组

1:查询每个城市的部门个数

select count(*) 个数,city from departments d,locations l where d.location_id=l.location_id group by city;

2:查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资

select department_name,d.manager_id,min(salary) from departments d,employees e where d.department_id=e.department_id and commission_pct is not null group by department_name,d.manager_id;

6、可以加排序

查询每个工种的工种名和员工的个数,并且按员工个数降序

select job_title,count(*) from employees e,jobs j where e.job_id=j.job_id group by job_title order by count(*) des

7、可以实现三表连接?

查询员工名、部门名和所在的城市

select last_name,department_name,city from employees e,departments d,locations l
where e.department_id=d.department_id and d.location_id=l.location_id
and city like 's%'
ORDER BY department_name DESC;

2、非等值连接 查询员工的工资和工资级别


SELECT salary,grade_level
FROM employees e,job_grades g
WHERE salary BETWEEN g.`lowest_sal` AND g.`highest_sal`
AND g.`grade_level`='A';