多表查询 —— 内连接&外连接&子查询

风陵南·2022-09-10 01:14·266 次阅读

多表查询 —— 内连接&外连接&子查询

连接查询

 

 

  内连接

    1、查询语法

-- 隐式内连接
select 字段列表 from 表1, 表2... where 条件;

-- 显式内连接
select 字段列表 from 表1 [INNER] join 表2 on 条件;

 

      (1)隐式内连接

-- 隐式内连接
select * from emp, dept where emp.dep_id = dept.did;

      (2)显式内连接

-- 显式外连接
select * from emp inner join dept on emp.dep_id = dept.did;

 

      

 

 

       多表查询中要查询单独字段时 ——  使用 emp.id  emp.name 这种格式  若表名称比较长,需要起别名

-- 查询 name, gender, salary, dname
select emp.name, emp.gender, emp.salary, dept.dname from emp, dept where emp.dep_id = dept.did;

-- 给表起别名 
select t1.name, t1.gender, t1.salary, t2.dname from emp t1, dept t2 where t1.dep_id = t2.did;

 

      

 

 

  外连接

    1、 外连接查询语法

-- 左外连接
select 字段列表 from 表1 left [outer] join 表2 on 条件

-- 右外连接
select 字段列表 from 表1 right [outer] join 表2 on 条件

    

     左外连接:

-- 左外连接
--  查询emp表所有数据和对应的部门信息
select * from emp left outer join dept on emp.dep_id = dept.did;

    

 

 

     右外连接:

-- 右外连接
--  查询dept表所有数据和对应的员工信息
Select * from dept right outer join emp on dept.did = emp.dep_id;

    

 

 

  子查询  

    1、 概念: 查询中嵌套查询,称嵌套查询为子查询

    

    2、 子查询根据查询结果不同,作用不同

      单行单列:作为条件值,使用 = 、!= 、>、< 等进行条件判断

select 字段列表 fromwhere 字段名 = ();

      例:

 

-- 查询工资高于 赵六 的员工信息
select * from emp where salary > (select salary from emp where name = '赵六');

 

 

 

      多行单列:作为条件值,使用 in 等关键字进行条件判断

 

select 字段列表 fromwhere 字段名 in (子查询);

 

      例:

 

-- 查询‘财务部‘和‘运营部‘所有的员工信息
select * from emp where dep_id in(select did from dept where dname = '财务部' or dname = '运营部');

 

 

 

      多行多列:作为虚拟表

select 字段列表 from (子查询) where 条件;

      例:

-- 查询入职日期是‘2015-11-11‘之后的员工信息和部门信息
select * from emp where join_date > '2015-11-11';    --

select * from emp  LEFT OUTER JOIN dept on emp.dep_id = dept.did;  -- 左外连接 ②
select * from emp, dept where emp.dep_id = dept.did;    -- 隐式内连接③
-- 合二为一 ① ② 或① ③ 替换掉 emp
select * from (select * from emp where join_date > '2015-11-11') t1 LEFT OUTER JOIN dept on t1.dep_id = dept.did; -- (左外连接)
select * from (select * from emp where join_date > '2015-11-11') t1, dept where t1.dep_id = dept.did;  -- (隐式内连接)

 

 

    

posted @   风陵南  阅读(266)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示