多表连接

1-创建一个部门表和员工表并插入数据

#创建部门表
CREATE TABLE department (
id int PRIMARY key  auto_increment,
dep_name varchar(10) not null
);


#向部门表中插入数据
insert into  department(dep_name) VALUES ('网盟营销'),('大数据中心')



#创建员工表
CREATE TABLE employee(
id int PRIMARY key auto_increment,
emp_name varchar(10) not null,
dep_id int
);


#向员工表中插入数据
insert into employee(emp_name,dep_id) VALUES('wangsiyu',1),('alex',2)

2 -查询员工的ID,姓名,部门的名称(隐式内连接)

select employee.id,emp_name,dep_name from employee,department 

WHERE department.id=employee.dep_id;

注意:对于两个表都同名的字段,应该在查询该字段的前面加上对应的表,否则电脑不知道你这个字段是哪个表的

3-内连接

select * from employee inner join department on employee.dep_id=department.id;

5-左连接

select * from employee left join department on employee.dep_id=department.id;

6-右连接:显示右表的全部记录

select * from employee right join department on employee.dep_id=department.id;

7-全连接:显示两个表的全部记录,没有对应的就用空表示

select * from employee full join department on employee.dep_id=department.id;

image

posted @ 2021-12-14 12:24  姚狗蛋  阅读(20)  评论(0编辑  收藏  举报