“各种连接(等值连接、内连接、外连接、左连接、右连接、全连接)”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第87行: 第87行:
 
on course.cnum = sc.cnum;
 
on course.cnum = sc.cnum;
 
</syntaxhighlight>上面两个SQL会得到相同的结果:
 
</syntaxhighlight>上面两个SQL会得到相同的结果:
[[文件:SQL 等值连接-显式内连接.png|无|缩略图|380x380像素]]
+
[[文件:SQL 等值连接-显式内连接.png|无|缩略图|388x388px|替代=]]
  
 +
=== 自连接 ===
 +
<syntaxhighlight lang="sql">
 +
select *
 +
from student stu1, student stu2
 +
where stu1.snum = stu2.snum
 +
</syntaxhighlight>
 +
[[文件:SQL 自连接 1.png|无|缩略图|536x536像素]]
  
 
=== 自然连接 ===
 
=== 自然连接 ===

2022年11月3日 (四) 08:54的版本

演示数据

学生表和学生数据

CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `snum` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `sage` tinyint(4) DEFAULT NULL,
  `sclass` smallint(6) NOT NULL,
  PRIMARY KEY (`snum`),
  UNIQUE KEY `student_num` (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `sql`.`student`
(`snum`,
`sname`,
`sage`,
`sclass`)
VALUES
(20201101,'张三',20,150),
(20201102,'李四',18,151),
(20201103,'王五',19,151),
(20201104,'赵六',18,150),
(20201105,'钱七',21,151),
(20201106,'孙八',20,152);

课程表和课程数据

create table course(
cid int not null auto_increment,
cnum int not null primary key,
cname varchar(20) not null,
unique key course_num (cid)
) engine = innodb auto_increment = 1 default charset = utf8;

INSERT INTO `sql`.`course`
(`cnum`,
`cname`)
VALUES
(101, '数据结构'),
(102, '编译原理'),
(103, '计算机网络'),
(105, '计算机组成原理'),
(106, '数据库');

学生课程关系表

CREATE TABLE `sc` (
  `scid` int(11) NOT NULL AUTO_INCREMENT,
  `snum` int(11) NOT NULL,
  `cnum` int(11) NOT NULL,
  `grade` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`snum`,`cnum`),
  UNIQUE KEY `scid` (`scid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `sql`.`sc`
(`snum`,
`cnum`,
`grade`)
VALUES
(20201101, 101, 85),
(20201102, 101, 55),
(20201103, 101, 90),
(20201101, 102, 88),
(20201102, 102, 75),
(20201103, 102, 58),
(20201101, 103, 72),
(20201102, 103, 80),
(20201103, 103, 92);


等值连接/显式内连接

等值连接也叫显式内连接,在进行多表联合查询时通过“=”(等号)来连接多张表之间字段对应的值,其产生的结果会出现重复列。

select *
from course,sc 
where course.cnum = sc.cnum;

select *
from course inner join sc 
on course.cnum = sc.cnum;

上面两个SQL会得到相同的结果:

生成缩略图出错:无法将缩略图保存到目标地点

自连接

select *
from student stu1, student stu2
where stu1.snum = stu2.snum
生成缩略图出错:无法将缩略图保存到目标地点

自然连接

外连接

内连接

全连接

左/右外连接