MySQL中的连接查询(等值连接)
1. 笛卡尔乘积
表1有m行数据,表2有n行数据,查询结果有m*n行数据。
2. 分类
(1)按年代分类
sql92标准:仅支持内连接
sql99标准(推荐):支持内连接、外连接(左外连接和右外连接)、交叉连接
(2)按功能分类
内连接:等值连接、非等值连接、自连接
外连接:左外连接、右外连接、全外连接
交叉连接
3. 等值连接
(1)查询女生名及其对应的男朋友名
SELECT
girlname,
boyname
FROM
boys,
girls
WHERE
girls.boyfriend_id=boys.girlfriend_id;
girlname,
boyname
FROM
boys,
girls
WHERE
girls.boyfriend_id=boys.girlfriend_id;
(2)查询员工名(last_name)和对应的部门名(department_name)————-(根据关联的id查询)
SELECT
last_name,
department_name
FROM
JDSC,
SNSC
WHERE
JDSC.`id`=SNSC.`id`;
last_name,
department_name
FROM
JDSC,
SNSC
WHERE
JDSC.`id`=SNSC.`id`;
(3)查询员工名(last_name)、工种号(job_id)、工种名(job_title) (员工表:JDSC 工作表:JOBSC)——为表起别名,提升简洁度,避免歧义
注意:
如果为表起了别名,则查询的字段不能使用原来的表名去限定。
上述两个表的顺序可互换
(4)查询有奖金的员工名、部门名
#员工名:last_name
#部门名:department_name
#奖金率:commissiom_pct
SELECT
last_name,
department_name,
commissiom_pct
FROM
employees e,
department d
WHERE
e.`department_id`=d.`department_id`
AND
e.`commissiom_pct` IS NOT NULL;
#部门名:department_name
#奖金率:commissiom_pct
SELECT
last_name,
department_name,
commissiom_pct
FROM
employees e,
department d
WHERE
e.`department_id`=d.`department_id`
AND
e.`commissiom_pct` IS NOT NULL;
(5)分组查询——查询每个城市的部门个数
#城市分组表名:city
#部门分组表名:departments
SELECT
COUNT(*) 个数,
city
FROM
departments d,
locations l
WHERE
d.`location_id`=l.`location_id`
GROUP BY
city;
#部门分组表名:departments
SELECT
COUNT(*) 个数,
city
FROM
departments d,
locations l
WHERE
d.`location_id`=l.`location_id`
GROUP BY
city;
(6)排序——查询每个工种的工种名和员工个数,并按员工个数降序
SELECT
job_title,
COUNT(*)
FROM
emloyees e,
jobs j
WHERE
e.`job_id`=j.`job_id`
GROUP BY
job_title
ORDER BY
COUNT(*) DESC;
job_title,
COUNT(*)
FROM
emloyees e,
jobs j
WHERE
e.`job_id`=j.`job_id`
GROUP BY
job_title
ORDER BY
COUNT(*) DESC;
(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%’;
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%’;
4. 总结
1)多表等值连接的结果为多表的交集部分
2)m表连接,至少需要n-1个连接条件
3)多表的顺序没有要求
4)一般需要为表起别名
5)可以搭配所有子句使用,例如排序、分组、筛选
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。