首先是对于查询的补充

分为以下四种:

1.group_concat()方法  分组之后 用于获取除分组以外其他的数据   也可以在括号内获取其他数据 并用逗号或者分割符隔开

2.concat()方法 用于分组之前 

3.concat_ws()方法   用于分组之前 多个字段相同分隔符情况、

4.as语法 在这里可以用作对字段进行重命名,但仅仅是用于展示,不会更改实际表数据

总结:as左边是字段则是字段别名 左边是表名则是表别名

今日主题:

建表 数据:

create table dep(
id int primary key auto_increment,
name varchar(20)
);

create table emp(
id int primary key auto_increment,
name varchar(20),
gender enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入数据
insert into dep values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into emp(name,gender,age,dep_id) values
('jason','male',18,200),
('egon','female',48,201),
('kevin','male',18,201),
('nick','male',28,202),
('owen','male',18,203),
('jerry','female',18,204);

 

查询各员工姓名及对应的部门名称

推导过程1

select * from emp,dep;  # 笛卡尔积  

推导过程2

select * from emp,dep where emp.dep_id=dep.id;

推导过程3

select emp.name,dep.name from emp,dep where emp.dep_id=dep.id;

 

联表:

inner join 内链接 (只链接两种表中都有对应的数据)

select * from emp inner join dep on emp.dep_id=dep.id;

left join 左链接 (以关键字左表为基础展示左表所有的数据 没有对应的以null填充)

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

right join 右链接 (以关键字右表为基础展示右表所有的数据 没有对应的以null填充)

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

union 全链接

select * from emp left join dep on emp.dep_id=dep.id
union
select * from emp right join dep on emp.dep_id=dep.id;

 

子查询:

将一张表的查询结果括号括起来当成另外一条SQL语句的条件

1.查询部门是技术或者人力资源的员工信息

方法1:连表操作
select emp.name,emp.age,dep.name from emp inner join dep on emp.dep_id=dep.id where dep.name in ('技术','人力资源');


方式2:子查询
1.先查询技术和人力资源id号
select id from dep where name in ('技术','人力资源');
2.再去员工表里面根据部门id号筛选出员工数据
select * from emp where dep_id in (select id from dep where name in ('技术','人力资源'));

涉及到多表查询只有两种方法

1.联表操作
2.子查询
并且很多复杂的查询甚至需要两者的结合