99版SQL语法格式区别于92版但是连接不是在用"=",它但语法格式:
SELECT 查询列表
FROM 表1 别名
[连接类型] join 表2 别名
on 链接条件
WHERE 数据筛选条件......以前讲过但其他部分
[连接类型]地关键字
内连接L: inner(还可以忽略)
外链接:
左外连接left[outer]
有外连接right[outer]
全外连接full[outer]
交叉连接 cross[outer]
1.内连接查询
SQL写法实现等值连接查询
案例:查询员工名和其对应所属的部门名
92版:
SELECT last_name,department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id;
99版:
SELECT last_name,department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;
案例:查询名字中包含e字母的员工名和其对象的部门名
SELECT last_name,department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id
WHERE last_name LIKE '%e%';
案例:查询所在部门个数大于3的城市名和部门个数
SELECT city,COUNT(*) FROM
locations l
INNER JOIN departments d
ON d.location_id=l.location_id
GROUP BY city
HAVING COUNT(*) >3;
案例:查询员工个数大于3的部门名和员工个数,降序排序
SELECT department_name ,COUNT(*) 员工个数 FROM
employees e
INNER JOIN departments d
ON e.department_id=d.department_id
GROUP BY department_name
HAVING COUNT(*) >3
ORDER BY 员工个数 DESC;
案例:查询员工名以及对应的工种名和部门名,按部门名降序排列
SELECT last_name,job_title,department_name
FROM employees e
INNER JOIN
departments d
ON e.department_id =d.department_id
INNER JOIN
jobs j
ON
j.job_id = e.job_id
ORDER BY department_name DESC;
99版非等值查询
案例:查询员工名,对应工资,对应级别
SELECT last_name,salary,grade_level
FROM employees e
INNER JOIN
job_grades g
ON e.salary BETWEEN g.lowest_sal AND g.highest_sal;
案例:查询同一个工资级别的员工的个数大于20的员工个数,并且按照工资级别降序排序
SELECT COUNT(*) 员工个数,g.grade_level
FROM employees e
INNER JOIN
job_grades g
ON e.salary BETWEEN g.lowest_sal AND g.highest_sal
GROUP BY g.grade_level
HAVING COUNT(*) >20
ORDER BY g.grade_level DESC;
案例:查询员工的名和其对应的直属领导的名字
SELECT e.last_name,m.last_name
FROM employees e
INNER JOIN
employees m
on e.manager_id = m.manager_id;
2.外连接查询
看这样的场景,在ta和tb两表中查询没有对应年龄数据的学生姓名和年龄
SELECT
tb.`name`,ta.`age`
FROM tb
INNER JOIN
ta
on tb.ta_id = ta.id
WHERE ta.id IS NULL;
无法解决
SELECT
tb.`name`,ta.`age`
FROM tb
LEFT OUTER JOIN
ta
on tb.ta_id = ta.id
WHERE ta.id IS NULL;
外连接的查询结果为主表中有的所有记录
如果外表中有对应数据,结果记录上显示对应数据
外表中没有对应的数据,结果记录上填充null
和内连接的区别:
内连接:当从表没有记录的时候,主、从表的记录都丢掉
外连接:
- 当从表没有记录的时候,会保留主表的记录,对应从表null
- 外连接:left join左边的是主表,右外连接right join右边的是主表
- 左外连接和右外连接上互通的所以掌握一个就好
案例:在ta和tb两表中查询没有对应年龄数据的学生姓名和年龄
SELECT
tb.`name`,ta.`age`
FROM tb
LEFT OUTER JOIN
ta
on tb.ta_id = ta.id
WHERE ta.id IS NULL;
案例:查询没有员工的部门
SELECT department_name,e.last_name FROM departments d
LEFT JOIN employees e
ON d.department_id = e.department_id
WHERE e.department_id IS NULL;
注意
本文用到的myemployees.sql 文件在MySQL实战2 语法、筛选条件和函数 附件中
网友评论