spl多表查询

1.多表查询概念:从多张表查询数据

2.分类:连接查询和子查询。

有两张表A、B

连接查询: 内连接 相当于查询A、B交集数据

例1:select * from emp,dept where emp.dep_id=dept.id;

外连接 左外连接:相当于查询A表所有数据和交集部分数据

右外连接:相当于查询B表所有数据和交集部分数据

子查询:查询中嵌套查询。

3.内连接(同时查询两张表的列)

隐式内连接 select 字段列表 from 表一,表二 where 条件;

如上面的例子:select * from emp,dept where emp.dep_id=dept.id;

在没有条件语句的情况下返回笛卡尔积(排列组合)

例2:select emp.name,emp.gender,dept.name from emp,dept where emp.dep_id=dept.id;

显式内连接 select 字段列表 from 表一 inner join 表二 on 条件;

例3:select * from emp iennr join dept on emp.dep_id = dept.id; innner可以省略

4.外连接

左外连接 select 字段列表 from 表1 left join 表2 on 条件;

例4:查询emp表所有数据和对应的部门信息

select * from emp left join dept on emp.dep_id = dept.id;

右外连接 select 字段列表 from 表1 right join 表2 on 条件;

例5:查询dept表所有数据和对应员工信息

select * from emp right join dept on emp.dep_id = dept.id;

或: select * from dept left join emp on emp.dep_id = dept.id;(工作中最常使用left join)

5.子查询

(1)概念:查询中嵌套查询。

子查询分为:单行单列 select 字段列表 from 表 where 字段名 = 子查询;

多行单列 select 字段列表 from 表 where 字段名 in 子查询;

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

例1:查询班级中成绩高于叶淑华的学生的信息:

select * from stus where score>(select score from stus where name = "叶淑华");

posted @ 2022-11-28 19:44  沐沐大帅  阅读(197)  评论(0)    收藏  举报