自连接
1、自连接(自然连接)是在同一个表上实行多表连接,进行自连接时须先将数据表虚拟化另一个表。
2.语法
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
where后面是等值连接。
内连接
语法:
SELECT a.column_name, b.column_name...
FROM table a (inner) jion table b
on a.common_field = b.common_field
where a.xxx = ""
and
...
区别
1、自然连接一定是等值连接,但等值连接不一定是自然连接。等值连接不把重复的属性除去;而自然连接要把重复的属性除去。
2、等值连接要求相等的分量,不一定是公共属性;而自然连接要求相等的分量必须是公共属性。
之前在学习内连接的时候,经常困惑是在什么样的场景下可以只用
InnerJoin:
在数据库表中存储数据的时候,有时候是多条数据属于同一个实体对象的,比如下面的score_table1、score_table2的分数记录表中,多条分数记录是属于一个学生的。找到高数和英语分数都在80分以上的同学:
score_table1:
studentId | subjectId | subjectName | score |
1 | 2 | 高数 | 87 |
1 | 3 | 英语 | 95 |
1 | 3 | 英语 | 67 |
2 | 4 | 线代 | 67 |
2 | 1 | 音乐 | 89 |
2 | 3 | 英语 | 76 |
select *
from score_table1 a (inner) join score_table1 b
on
a.studentId = b.studentId
where
a.subjectId = "2"
and a.score > 80
and b.subjectId = "3"
and b.score > 80
score_table2:
studentId | mathScore | englishScore | linearAlgebraScore |
1 | null | 78 | null |
1 | 95 | null | null |
1 | null | null | 32 |
2 | 32 | null | null |
2 | null | null | 43 |
2 | null | 78 | null |
select *
from score_table2 a (inner) join score_table2 b
on
a.studentId = b.studentId
where
a.mathScore > 80
and b.englishScore > 80