进阶6连接查询

含义:又称为多表查询,当查询的字段来自多个表时,就会用到连接查询
笛卡尔乘积现象:表一有m 行,表二有n行,结果有 m*n行
发生原因:没有有效的连接条件
如何避免:添加有效的连接条件
特点:多表等值连接的结果为多表的交集部分
N表的连接,至少需要n-1个条件
多表的顺序没有要求
多表连接的时候一般需要起别名
可以搭配前面介绍的所有子句来使用,比如排序。分组。筛选

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

在这里插入图片描述

按功能进行分类

内连接:等值连接,非等值连接,自连接
外连接:左外连接,右外连接,全外连接
交叉连接

等值连接:

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

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

select last_name,department_name
from empolyees,department 
where employees.department_id=department.department_id;

请添加图片描述
,注意:如果为表起了别名,则查询的字段就不能使用原来的表名来限定

可以加筛选吗?

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

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

案例二:

查询城市名中第二个字符名为o的部门
select department_name,city
from departments d,location l
where d.location_id=l.location_id
and city like '_o%'

可不可以分组?

案例一:查询每个城市的部门个数

select count(*)  个数,city
from department d, location l
group by city;

#案例二:
查询出有奖金的部门名和部门的领导编号,以及该部门的最低工资

 select department_name,d.manger_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.manger_id;

例:查询每个工种的工种名和员工的个数,并且按员工的个数进行排序

select  job_title,count(*)
from employees e,jobs j
where e.job_id=j.jod_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
and city like 's%';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值