SQL 连接的类型(如左连接、右连接和全连接)以及笛卡尔连接和自连接已在其他章节中讨论过。在这篇文章中,我们将探讨剩余的两种重要类型:等值连接(EQUI JOIN)和非等值连接(NON-EQUI JOIN)。让我们逐一进行深入了解。
SQL 连接
- 等值连接
- 非等值连接
示例
为了更好地理解,让我们考虑下面给出的两个表。
表名 — Student (学生表)
在这个表中,包含 id、name、class 和 city 这些字段。
Select * from Student;
name
city
—
—
Hina
Delhi
Megha
Delhi
Gouri
Delhi表名 — Record (记录表)
在这个表中,包含 id、class 和 city 这些字段。
Select * from Record;
class
—
3
2
2
1. 等值连接 (EQUI JOIN)
等值连接基于相关表之间列值的相等性或匹配来创建连接。我们也可以使用 JOIN 结合 ON 关键字来创建等值连接,通过提供列名及其所属表来检查相等性(使用等号 =)。
语法:
SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
示例:
SELECT student.name, student.id, record.class, record.city
FROM student, record
WHERE student.city = record.city;
或者,我们也可以使用以下标准语法:
语法:
SELECT column_list
FROM table1
JOIN table2
[ON (join_condition)]
示例:
SELECT student.name, student.id, record.class, record.city
FROM student
JOIN record
ON student.city = record.city;
输出结果:
id
city
—
—
3
Delhi
4
Delhi
6
Delhi
3
Delhi
4
Delhi
6
Delhi
3
Delhi
4
Delhi
6
Delhi## 2. 非等值连接 (NON EQUI JOIN)
非等值连接使用除等号 (=) 以外的比较运算符(如 >, =, <=)结合特定条件来执行连接操作。
语法:
SELECT *
FROM table_name1, table_name2
WHERE table_name1.column [> | = | <= ] table_name2.column;
示例:
SELECT student.name, record.id, record.city
FROM student, record
WHERE Student.id < Record.id ;
输出结果:
id
—
9
9
9
10
10
10
12
12
12