mysql-----多表查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql-----多表查询相关的知识,希望对你有一定的参考价值。
一、多表连接查询
#重点 : 外链接语法 select 字段列表 from 表1 inner | left | right join 表2 on 表1.字段=表2.字段;
1、交叉链接:不适用任何匹配条件。生成笛卡尔积 select * from employee,department; 2、内连接:只连接匹配的行 select * from employee,department where employee.dep_id=department.id; #不用这种形式 select * from employee inner join department on employee.dep_id=department.id; 3、外链接之左连接:优先显示左表全部记录 select * from employee left join department on employee.dep_id=department.id; 4、外链接之右连接:优先显示右表全部记录 select * from employee right join department on employee.dep_id=department.id; 5、全外链接:显示左右两个表全部记录 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;
二、符合条件连接查询
#示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出公司所有部门中年龄大于25岁的员工 select employee.name,employee.age from employee,department where employee.dep_id=department.id and age>25; select t1.name,t1.age,t2.name from employee as t1 left join department as t2 on t1.dep_id=t2.id and age>25; #示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示 select employee.id,employee.name,employee.age,department.name from employee,department where employee.dep_id = department.id and age > 25 order by age asc;
三、子查询
#1:子查询是将一个查询语句嵌套在另一个查询语句中。 #2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。 #3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字 #4:还可以包含比较运算符:= 、 !=、> 、<等
1、带in关键字的子查询
#查询employee表,但dep_id必须在department表中出现过 select * from employee where dep_id in (select id from department);
2、带比较运算符的子查询
#比较运算符:=、!=、>、>=、<、<=、<> #查询平均年龄在25岁以上的部门名 select id,name from department where id in (select dep_id from employee group by dep_id having avg(age)>25); #查看技术部员工姓名 select name from employee where dep_id in (select id from department where name=‘技术‘); #查看不足1人的部门名 select name from department where id in ( select dep.id from department dep left join employee emp on dep.id = emp.dep_id group by dep.id having count(emp.id) < 1 ); select * from department where id not in ( select dep_id from employee group by dep_id having count(id) >= 1 );
3、带exists关键字的子查询
exists关键字表示存在。在使用exists关键字时,内层查询语句不返回查询结果。而是返回一个真假值。True或False
当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询
#deparment表中存在dep_id=200时,True select * from employee where exists (select id from department where id=200); 因为括号中为TRUE,返回的值为select * from employee语句的结果 select * from employee where exists (select id from department where id=204); 因为括号中为Flase,外层不查询,返回空集Empty set
以上是关于mysql-----多表查询的主要内容,如果未能解决你的问题,请参考以下文章