按年代分类
①SQL92标准:仅支持内连接
②SQL99标准(推荐):支持内连接+外连接(不支持全外连接)+交叉连接
按功能分类
①内连接(包括等值连接、非等值连接和自连接)
②外连接(包括左外连接、右外连接和全外连接)
③交叉连接
SELECT * FROM beauty;
SELECT * FROM boys;
SELECT NAME,boyname FROM boys,beauty;
这样写会发生笛卡尔乘积现象,应写为下面这种:
SELECT NAME,boyname FROM boys,beauty
WHERE beauty.boyfriend_id=boys.id;
①多表等值连接的结果为多表的交集部分;
②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`;
案例:查询员工名、工种号、工种名
SELECT last_name,e.job_id,job_title
FROM employees AS e,jobs j #生成虚拟视图
WHERE e.`job_id`=j.`job_id`;
SELECT e.last_name,e.job_id,j.job_title
FROM jobs j,employees e
WHERE e.`job_id`=j.`job_id`;
案例1:查询有奖金的员工名和部门名
SELECT last_name,department_name
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%';
案例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;
案例:查询每个工种的工种名和员工的个数,并且按员工个数降序
SELECT job_title,COUNT(*)
FROM employees e,jobs j
WHERE e.`job_id`=j.`job_id`
GROUP BY job_title
ORDER BY COUNT(*) DESC;
案例:查询员工名、部门名和所在城市
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`;
案例1:查询员工的工资和工资级别
SELECT salary,grade_level
FROM employees e,job_grades g
WHERE e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`;
create table:
由于原数据库中没有工资级别的表,所以要进行创建,create table语句的语法结构如下:
create table <表名>
(<列名1> <数据类型> <该列所需约束(可选)>,
<列名2> <数据类型> <该列所需约束>
....);
进行工资级别表的创建:
CREATE TABLE job_grades
(grade_level VARCHAR(3),
lowest_sal INT,
highest_sal INT);
INSERT INTO job_grades
VALUES ('A', 1000, 2999);
INSERT INTO job_grades
VALUES ('B', 3000, 5999);
INSERT INTO job_grades
VALUES('C', 6000, 9999);
INSERT INTO job_grades
VALUES('D', 10000, 14999);
INSERT INTO job_grades
VALUES('E', 15000, 24999);
INSERT INTO job_grades
VALUES('F', 25000, 40000);
执行后刷新,则表默认创建在当前库,再进行查看:
SELECT * FROM job_grades;
案例:查询员工名和上级的名称
SELECT e.employee_id 员工,e.last_name,m.employee_id 上级,m.last_name
FROM employees e,employees m#e为员工表,m为领导表
WHERE e.manager_id=m.employee_id;