第15节--连接查询

连接查询

含义:又称多表查询(多表连接),当查询的字段来自多个表时,就会用到连接查询

笛卡尔乘积现象:表1有m行,表2有n,结果为m*n行;发生原因:没有有效的连接条件;如何避免:添加有效的连接条件

连接查询分类:

按年代分类:

  SQL92标准(仅支持内连接)

  SQL99标准(支持内连接+外连接+交叉连接)【推荐此标准】

按功能分类:

    内连接:等值连接,非等值连接,自连接

    外连接:左外连接,右外连接,全外连接

交叉连接

 

sql92语法:

等值连接 案例:

(等值连接):查询女神名和对应的男神名
select Name,boyName
from boys,beauty
where beauty.boyfriend_id=boys.id;
(等值连接加上筛选条件):查询有奖金的员工名和部门名

select last_name,department_name
from employees e, departments d
where e.department_id=d.department_id
and commission_pct is not null;

备注:mysql查询中可以为表漆别名,有利于提高语句的简洁度,区分多个重名的字段。如果为表起了别名,则查询的字段就不能使用原来的表名去限定;
等值连接加分组:查询每个城市的部门个数

select count(*), city
from departments d, locations l
where d.location_id=l.location_id
group by city;
(等值连接加排序): 查询每个工种的工种名和员工个数,并按员工个数排序

select count(*) c, job_title
from employees e,jobs j
where e.job_id=j.job_id
group by job_title
order by c;
(三表连接):查询员工名,部门名,和所在城市

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;

》非等值连接 案例

查询员工的工资和工资级别

select salary, grade_level
from employees e, job_grades g
where salary between lowest_sal and highest_sal;

》自连接

查询员工名和上机的名称

select e.last_name, m.last_name
from employees e, employees m
where e.manager_id=m.employee_id;

SQL 99语法

》内连接;分类:等值连接,非等值连接,自连接

语法: select 查询列表 from 表1 别名

    (inner)join 表2 别名 on 连接条件

    where 筛选条件

    group by 分组列表

    having 分组后的筛选

    order by 排序列表

    limit 子句;

特点:

  ① 表的顺序可以调换

  ②内连接的结果为多表的交集

  ③n表连接至少需要n-1个连接条件

》外连接

语法:select 查询列表

   from 表1 别名

   left/right/ full (outer) join 表2 别名

   on 连接条件

   where 筛选条件

     group by 分组列表

     having 分组后的筛选

     order by 排序l列表

     limit 子句;

特点:①查询的结果为主表中所有的行,从表中和它匹配的将显示匹配行,如果从表没有匹配的则显示null

           ②left join左边为主表;right join右边为主表;full join两边都是主表

           ③一般用于查询除了交集部分的剩余不匹配的行

》交叉连接

语法:select 查询列表

from 表1 别名

cross join 表2 别名;(类似于笛卡尔乘积)

 

posted @ 2020-04-08 16:25  白云~  阅读(146)  评论(0编辑  收藏  举报