当前位置:网站首页>MySQL winter vacation self-study 2022 11 (9)

MySQL winter vacation self-study 2022 11 (9)

2022-07-06 02:25:00 Crane paper thousand

Self association query

mysql Sometimes, when querying information, you need to perform association query on the table itself , That is, a table is associated with itself , Use one table as multiple tables . Note that the table must be aliased during self association .

preparation

use mydb3;

create table t_sanguo
(
	eid int primary key,
	ename varchar(20),
	manager_id int,
	foreign key (manager_id) references t_sanguo(eid) # Add self association query 
);

insert into t_sanguo values(1,' Liu Xie ',null);
insert into t_sanguo values(2,' Liu bei ',1);
insert into t_sanguo values(3,' Guan yu ',2);
insert into t_sanguo values(4,' Zhang Fei ',2);
insert into t_sanguo values(5,' Cao Cao ',1);
insert into t_sanguo values(6,' Xu Chu ',5);
insert into t_sanguo values(7,' Dianwei ',5);
insert into t_sanguo values(8,' king of Wu in the Three Kingdoms Era ',1);
insert into t_sanguo values(9,' Zhou Yu ',8);
insert into t_sanguo values(10,' Lu Su ',8);

Open the reverse table to the model

part1

--  Make association query 
--  Query the information of each person in the three countries and his superiors , Such as : Guan yu   Liu bei 
select a.ename,b.ename from t_sanguo a,t_sanguo b where a.manager_id = b.eid;
select a.ename,b.ename from t_sanguo a join t_sanguo b on a.manager_id = b.eid;

  The operation results are as follows

 part2

--  Query all tasks and superiors , Including Liu Xie 
select a.ename,b.ename from t_sanguo a left join t_sanguo b on a.manager_id = b.eid;

 part3

--  Query all people , The superior , Superior   such as :  Zhang Fei , Liu bei , Liu Xie 
select a.ename,b.ename,c.ename
from t_sanguo a 
	left join t_sanguo b on a.manager_id = b.eid
	left join t_sanguo c on b.manager_id = c.eid;

 

原网站

版权声明
本文为[Crane paper thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140023140869.html