参考资料

  1. MySQL 连接的使用详细说明以及案例
  2. MySQL DELETE 语句详细说明以及案例
  3. MySQL 正则表达式详细说明以及案例
  4. MySQL UPDATE 更新详细说明以及案例
  5. MySQL 函数详细说明以及案例
  6. MySQL 创建数据表详细说明以及案例
  7. MySQL 命令详细说明以及案例
  8. MySQL WHERE 子句详细说明以及案例

MySQL 连接的使用详细说明

MySQL 连接用于将多个表中的数据组合在一起。常见的连接类型包括:

  1. 内连接(INNER JOIN):返回两个表中匹配的行。

  2. 左连接(LEFT JOIN):返回左表中的所有行,即使右表中没有匹配的行。

  3. 右连接(RIGHT JOIN):返回右表中的所有行,即使左表中没有匹配的行。

  4. 全连接(FULL JOIN):返回两个表中的所有行,即使没有匹配的行(MySQL 不支持 FULL JOIN,但可以通过 UNION 实现)。

  5. 交叉连接(CROSS JOIN):返回两个表的笛卡尔积。

案例

假设有两个表:studentsscores

表结构

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

CREATE TABLE scores (
    student_id INT,
    subject VARCHAR(50),
    score INT
);

插入数据

INSERT INTO students (id, name) VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');

INSERT INTO scores (student_id, subject, score) VALUES
(1, 'Math', 90),
(1, 'Science', 85),
(2, 'Math', 78),
(3, 'Science', 92);

1. 内连接(INNER JOIN)

SELECT students.name, scores.subject, scores.score
FROM students
INNER JOIN scores ON students.id = scores.student_id;

结果

name    | subject | score
--------|---------|------
Alice   | Math    | 90
Alice   | Science | 85
Bob     | Math    | 78
Charlie | Science | 92

2. 左连接(LEFT JOIN)

SELECT students.name, scores.subject, scores.score
FROM students
LEFT JOIN scores ON students.id = scores.student_id;

结果

name    | subject | score
--------|---------|------
Alice   | Math    | 90
Alice   | Science | 85
Bob     | Math    | 78
Charlie | Science | 92

3. 右连接(RIGHT JOIN)

SELECT students.name, scores.subject, scores.score
FROM students
RIGHT JOIN scores ON students.id = scores.student_id;

结果

name    | subject | score
--------|---------|------
Alice   | Math    | 90
Alice   | Science | 85
Bob     | Math    | 78
Charlie | Science | 92

4. 全连接(FULL JOIN)

MySQL 不支持 FULL JOIN,但可以通过 UNION 实现:

SELECT students.name, scores.subject, scores.score
FROM students
LEFT JOIN scores ON students.id = scores.student_id
UNION
SELECT students.name, scores.subject, scores.score
FROM students
RIGHT JOIN scores ON students.id = scores.student_id;

结果

name    | subject | score
--------|---------|------
Alice   | Math    | 90
Alice   | Science | 85
Bob     | Math    | 78
Charlie | Science | 92

5. 交叉连接(CROSS JOIN)

SELECT students.name, scores.subject, scores.score
FROM students
CROSS JOIN scores;

结果

name    | subject | score
--------|---------|------
Alice   | Math    | 90
Alice   | Science | 85
Bob     | Math    | 78
Bob     | Science | 92
Charlie | Math    | 90
Charlie | Science | 85
Alice   | Math    | 78
Alice   | Science | 92
Bob     | Math    | 90
Bob     | Science | 85
Charlie | Math    | 78
Charlie | Science | 92

这些案例展示了如何使用不同类型的连接来组合表中的数据。