mysql之多表查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql之多表查询相关的知识,希望对你有一定的参考价值。
#部门表 create table department( id int, name varchar(20) ); #员工表 create table employee( id int primary key auto_increment, name varchar(20), sex enum(‘male‘,‘female‘) not null default ‘male‘, age int, dep_id int ); insert into department values (200,‘技术‘), (201,‘人力资源‘), (202,‘销售‘), (203,‘运营‘); insert into employee(name,sex,age,dep_id) values (‘egon‘,‘male‘,18,200), (‘alex‘,‘female‘,48,201), (‘wupeiqi‘,‘male‘,38,201), (‘yuanhao‘,‘female‘,28,202), (‘liwenzhou‘,‘male‘,18,200), (‘jingliyang‘,‘female‘,18,204)
多表链接查询
select 字段 from 表1 inner|left|right join 表2 on 表1.字段 = 表2.字段;
笛卡尔积
select * from department,employee; select * from employee,department;
内连接
select * from employee,department where employee.dep_id = department.id; select employee.name from employee,department where employee.dep_id = deparment.id and department.name = ‘技术‘;
左链接
select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id = department.id;
右链接
select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id = department.id;
全外连接 显示左右两表全部记录
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;
条件查询
select employee.name,department.name from employee inner join department on employee.dep_id = department.id where age > 25; select employee.id,employee.name,employee.age,department.name from employee,department where employee.dep_id = department.id and age > 25 order by age desc;
子查询
select * from employee inner join department on employee.dep_id = department.id; select employee.name from employee inner join department on employee.id = department.id where department.name = ‘技术‘;
子查询的另外的方法
select id from department where name = ‘技术‘; select name from employee where dep_id = (select id from department where name = ‘技术‘);
带in关键字的查询
select id,name from department where id in (select dep_id from employee group by dep_id having avg(age) > 25); select department.name from department inner join employee on department.id = employee.dep_id group by department.name having avg(age)>25; select name from employee where dep_id in (select id from department where name = ‘技术‘); select name from department where id not in (select distinct dep_id from employee);
带比较运算符的子查询
select name,age from employee where age > (select avg(age) from employee);
带exists关键字的查询
select * from employee where exists (select id from department where id = 200); select * from employee where exists (select id from department where id = 204);
以上是关于mysql之多表查询的主要内容,如果未能解决你的问题,请参考以下文章