MySQL多表查询

实例:

一.创建表

创建表dept3

create table if not exists dept3(
    ->  deptno varchar(20) primary key ,
    -> name varchar(255)  CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
    -> );

插入数据

insert into dept3 values('1001','研发部');

insert into dept3 values('1002','销售部');

insert into dept3 values('1003','财务部');

insert into dept3 values('1004','人事部');
 

创建表emp3

create table if not exists emp3(
    -> eid varchar(20) primary key ,
    ->  ename varchar(255)  CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    ->  age int,
    -> dept_id varchar(20)
    -> );

插入数据

insert into emp3 values('2','段誉',21, '1001');

insert into emp3 values('1',' 乔峰 ',20, '1001');

insert into emp3 values('3','虚竹',23, '1001');

insert into emp3 values('4','阿紫',18, '1001');

insert into emp3 values('5','扫地僧',85, '1002');

insert into emp3 values('6','李秋水',33, '1002');

 insert into emp3 values('7','鸠摩智',50, '1002'); 

 insert into emp3 values('8','天山童姥',60, '1003');

insert into emp3 values('9','慕容博',58, '1003');

insert into emp3 values('10','丁春秋',71, '1005');

MySQL多表查询_第1张图片


MySQL多表查询_第2张图片

1、查询每个部门的所属员工
MySQL多表查询_第3张图片

 select emp3.*,dept3.* from dept3 inner join emp3 on emp3.dept_id = dept3.deptno;

2、查询研发部门的所属员工
MySQL多表查询_第4张图片
select emp3.*,dept3.* from dept3 inner join emp3 on emp3.dept_id = dept3.deptno where name IN('研发部');
 

 

3、查询研发部和销售部的所属员工
MySQL多表查询_第5张图片
 select emp3.*,dept3.* from dept3 inner join emp3 on emp3.dept_id = dept3.deptno where name IN('研发部') or name IN('销售部');

 

4、查询每个部门的员工数,并升序排序
MySQL多表查询_第6张图片
select name,count(*) from dept3 inner join emp3 on emp3.dept_id = dept3.deptno group by
name order by count(*) asc;

 

5、查询人数大于等于3的部门,并按照人数降序排序

MySQL多表查询_第7张图片

 

 select name,count(*) from dept3 inner join emp3  on emp3.dept_id = dept3.deptno  group by name HAVING count(*) >= 3 order by count(*) desc;

 


 

你可能感兴趣的:(mysql,数据库)