一.多表查询
如果直接查询
select name,course_name from student,course;
会产生笛卡尔集
笛卡尔集产生条件:
1.省略连接条件
2.连接条件无效
3.所有表中的所有行互相连接
为了避免笛卡尔集,可以在where
中加入有效的连接条件
使用on子句创建链接
内连接:[inner] join on
外连接:
· 左外连接:left[outer]join on
· 右外连接:right[outer]join on
连接单个表:
select gril.id,grilname,boyname from gril inner join boy on gril.boyfriend_id=boy.id;
连接多个表:
select employee_id,city,department_name
from employees
join departments
on department.departments_id=employees.department_id
join locations
on departments.location_id = locations.location_id;
子查询
例如:
select last_name
from employees
where salary > (select salary from employees where last_name = 'Able');
多行子查询
.返回多行
.使用多行比较操作符
in/not in
等于列表中的任意一个
any/some
和子查询返回的某一值比较
all
和子查询返回的所有值比较
例如:使用any
操作符
返回其他部门中比job.id
为IT_PROG
部门任一工资低的员工的信息
select employee_id,last_name,job_id,salary
from employees
where salary < any(select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
使用all
操作符
返回其他部门中比job.id
为IT_PROG
部门所有工资低的员工的信息
select employee_id,last_name,job_id,salary
from employees
where salary < all(select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';