多表查询

一、多连接查询
 
链接语法:
select 字段  from t1  inner/left/right  join t2 
            on  t1.字段 = t2.字段; (连接条件)
 
准备表:
1、交叉连接:不使用任何的匹配条件,会生成笛卡尔积
select * from employee,department;
department中的每条记录,都对应employee中的所有记录
2、inner  join 内连接:只连接匹配的行
通过条件,取两张表的交集
select  * from employee  inner  join department  on employee.dep_id=department.id;  
#等同于 select * from employee,department  where employee.dep_id=department.id;
3、left  join 左连接:在内连接的基础上,保留左表的记录,没有匹配到右表的为NULL
select * from employee left  join department  on employee.dep_id=department.id;

4、right  join 右连接:在内连接的基础上,保留右边的记录,没匹配到的为NULL

select * from employee  right join department  on employee.dep_id=department.id;

5、union 全外连接:取并集,(在内连接的基础上,加上差集)

注意:mysql 不支持全外连接的 full join,一些其他的数据库管理软件支持
通常和left join、right join 一起来使用
 
强调:mysql中用union 实现全外连接
select * from employee left join department on employee.dep_id=department.id
union 
select * from employee right join department on employee.dep_id=department.id;
#相当于对左右外连接取并集
备注:union all 相当于左右连接相加,union会去掉相同 

6、关键字优先级

select distinct  字段  from 左表 inner/left/right  join  右表  on 连接条件
                        where        约束条件
                        group by   分组字段
                        having       过滤条件
                        order by    排序字段
                        limit          限制条件
顺序:1、先找到两张表,生成笛卡尔积,得到表1
          2、按照on 得到相同部分 ,得到表2
          3、join ,在表2基础上保留左表或右表的记录,得到表3
          4、where    
          5、group by
          6、having
          7、select (distinct)
          8、order by
          9、limit

二、子查询
 
#1、子查询是将1个查询语句嵌套在另一个查询语句中,用括号括入
#2、内层查询语句的查询结果,可以为外层查询语句提供查询条件
#3、子查询可以包含:in、not in、any、all、exists、not exists等关键字,还可以包含比较运算符:= 、 !=、> 、<等。(就和正常的一条查询一样)
 
1、in 
select  * from employee where dep_id in (select id  from  department);
 
2、比较运算符
#查看不足1人的部门名
select  name from department
        where  id  not  in
            ( select dep_id from employee group by dep_id having count(id)>=1);
 
3、exists
使用exist关键字时,内层查询语句不返回查询的记录,而是返回一个布尔值
当返回True时,外层语句将进行查询,False时外层不进行查询
select * from employee 
        where  exists
            (select id from department where id=205);
 
##备注:从aaa.sql文件导入数据
source /root/aaa.sql
posted @ 2017-10-29 23:48  唐宋元明卿  阅读(62)  评论(0)    收藏  举报