mysql之多表查询
多表查询
一.连接查询
1.内连接
用左边表的记录去匹配右边表的记录,符合条件的才显示,内连接又分隐式内连接和显示内连接两种
1)隐式内连接 不使用join关键字,条件使用where指定
语法:select 字段名 from 左表,右表 where 条件
ps:查询员工的姓名和所在部门的名称
select a.id,dep_id,name from employee a,department b where a.dep_id=b.id

2)显示内连接 使用innet join ... on语句
语法:select 字段名 from 左表 join 右表 on 条件
ps:查询 小小度的id,年龄,姓名,工资,入职日期,部门
select a.id,a.age,a.name,a.salary,a.add_company,b.dep_name from
employee a join department b on a.dep_id=b.id and a.name='小小度'

2.外连接
1)左外连接(显示左表所有数据,包括null) 使用 left join ... on
语法:select 字段名 from 左表 left join 右表 on 条件
2)右外连接(显示右表所有数据,包括null) 使用 right join ... on
语法:select 字段名 from 左表 right join 右表 on 条件
ps:当有一个员工没有部门的时候使用以下语句查询不到这个员工(右边为查询的表)
select a.*,b.dep_name from employee a,department b where a.dep_id=b.id


所以我们需要使用左外链接或者右外链接查询所有员工(如图)
select a.*,b.dep_name from employee a left join department b on a.dep_id=b.id //左外链接 select a.*,b.dep_name from department b right join employee a on a.dep_id=b.id //右外链接

二.子查询
一条select语句结果作为另一条select语句的一部分
语法:select 字段 from 表 where 字段 运算符(select 字段 from 表)
ps:查询工资最高的员工信息
select a.*,b.dep_name from employee a,department b where salary=(select max(salary) from employee) and a.dep_id=b.id

ps:查询工资高于小小度(工资6543)的员工 select *from employee a where salary>(select salary from employee where name='小小度') //大于
select *from employee a where salary<(select salary from employee where name='小小度') //小于

ps:查询工资大于6000的人来自那些部门
select a.*,b.dep_name from employee a,department b where salary>6000 and a.dep_id=b.id
ps:统计各部门的人数
select d.dep_name 部门, (SELECT count(*) from employee e WHERE e.dep_id=d.id) 人数 from department d


浙公网安备 33010602011771号