SQL | 等值连接与非等值连接详解

SQL 连接的类型(如左连接、右连接和全连接)以及笛卡尔连接和自连接已在其他章节中讨论过。在这篇文章中,我们将探讨剩余的两种重要类型:等值连接(EQUI JOIN)和非等值连接(NON-EQUI JOIN)。让我们逐一进行深入了解。

SQL 连接

  • 等值连接
  • 非等值连接

示例

为了更好地理解,让我们考虑下面给出的两个表。

表名 — Student (学生表)

在这个表中,包含 id、name、class 和 city 这些字段。

Select * from Student;
id

name

class

city

3

Hina

3

Delhi

4

Megha

2

Delhi

6

Gouri

2

Delhi表名 — Record (记录表)

在这个表中,包含 id、class 和 city 这些字段。

Select * from Record;
id

class

city —

— 9

3

Delhi 10

2

Delhi 12

2

Delhi

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;

输出结果:

name

id

class

city

Hina

3

3

Delhi

Megha

4

3

Delhi

Gouri

6

3

Delhi

Hina

3

2

Delhi

Megha

4

2

Delhi

Gouri

6

2

Delhi

Hina

3

2

Delhi

Megha

4

2

Delhi

Gouri

6

2

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 ;

输出结果:

name

id

city —

— Hina

9

Delhi Megha

9

Delhi Gouri

9

Delhi Hina

10

Delhi Megha

10

Delhi Gouri

10

Delhi Hina

12

Delhi Megha

12

Delhi Gouri

12

Delhi
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/42604.html
点赞
0.00 平均评分 (0% 分数) - 0