📅  最后修改于: 2020-11-12 00:45:38             🧑  作者: Mango
在SQL中联接多个表是一项棘手的任务。如果您需要在单个SQL查询中连接两个以上的表,可能会更加困难,我们将分析如何使用INNER JOIN从多个表中检索数据。在本节中,我们使用了两种方法来连接SQL中的三个或更多表。
我们将创建三个表,如下所示:
create table student(s_id int primary key, s_name varchar(17));
insert into student values(1, 'Jack');
insert into student values(2, 'Rithvik');
insert into student values(3, 'Jaspreet');
insert into student values(4, 'Praveen');
insert into student values(5, 'Bisa');
insert into student values(6, 'Suraj');
学生桌
在上表中,s_id是主键。
create table marks(school_id int primary key, s_id int, score int, status varchar(20));
insert into marks values(1004, 1, 23, 'fail');
insert into marks values(1008, 6, 95, 'pass');
insert into marks values(1012, 2, 97, 'pass');
insert into marks values(1016, 7, 67, 'pass');
insert into marks values(1020, 3, 100, 'pass');
insert into marks values(1025, 8, 73, 'pass');
insert into marks values(1030, 4, 88, 'pass');
insert into marks values(1035, 9, 13, 'fail');
insert into marks values(1040, 5, 16, 'fail');
insert into marks values(1050, 10, 53, 'pass');
标记表
在上表中,school_id是主键,s_id是外键。
create table details(address_city varchar(20), email_ID varchar(20), school_id int, accomplishments varchar(50));
insert into details values('Bangalore', 'jsingh@jtp.com',
1020, 'ACM ICPC selected');
insert into details values('Hyderabad', 'praveen@jtp.com',
1030, 'Geek of the month');
insert into details values('Delhi', 'rithvik@jtp.com',
1012, 'IOI finalist');
insert into details values('Chennai', 'om@jtp.com',
1111, 'Geek of the year');
insert into details values('Banglore', ' suraj@jtp.com',
1008, 'IMO finalist');
insert into details values('Mumbai', 'sasukeh@jtp.com',
2211, 'Made a robot');
insert into details values('Ahmedabad', 'itachi@jtp.com',
1172, 'Code Jam finalist');
insert into details values('Jaipur', 'kumar@jtp.com',
1972, 'KVPY finalist');
在上表中,school_id是外键。
有两种方法可以在SQL中联接三个或更多表:
这里应用了相同的逻辑,该逻辑用于连接两个表,即,连接n个表的最小连接语句数为(n-1)。
select s_name, score, status, address_city, email_id,
accomplishments from student s inner join mark m on
s.s_id = m.s_id inner join details d on
d.school_id = m.school_id;
输出:
在父子关系中,我们使用where子句连接两个或多个表。在一个表中创建X列作为主键,在另一个表中创建外键
查看所创建的表:s_id是学生表中的主键,而标记表中的外键。 (学生(父母)-标记(孩子))。 school_id是标记表中的主键,而学生表中的外键。 (标记(父级)-详细信息(子级))。
查询:
select s_name, score, status, address_city,
email_id, accomplishments from student s,
marks m, details d where s.s_id = m.s_id and
m.school_id = d.school_id;
输出: