MySQL Left Outer Join

在MySQL中,LEFT OUTER JOIN是一种常用的SQL join语句,用于将两个或多个表中的数据进行连接。LEFT OUTER JOIN返回左表中的所有行,以及符合连接条件的右表中的行。如果右表中没有与左表匹配的行,则结果集将包含NULL值。

语法

SELECT columns
FROM table1
LEFT OUTER JOIN table2
ON table1.column = table2.column;
  • SELECT columns:要查询的列
  • FROM table1:左表
  • LEFT OUTER JOIN table2:右表
  • ON table1.column = table2.column:连接条件

示例

假设有两个表studentsscores,结构如下:

### students表

| id | name   | age |
|----|--------|-----|
| 1  | Alice  | 20  |
| 2  | Bob    | 21  |
| 3  | Charlie| 22  |

### scores表

| student_id | subject | score |
|------------|---------|-------|
| 1          | Math    | 90    |
| 1          | English | 85    |
| 3          | Math    | 95    |

通过LEFT OUTER JOIN查询学生及其成绩:

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

结果如下:

id name subject score
1 Alice Math 90
1 Alice English 85
2 Bob NULL NULL
3 Charlie Math 95

关系图

erDiagram
    STUDENTS {
        int id
        varchar name
        int age
    }
    SCORES {
        int student_id
        varchar subject
        int score
    }
    STUDENTS ||--o{ SCORES : "1"

通过上述示例,我们可以看到LEFT OUTER JOIN的作用,连接左表和右表,如果右表中没有匹配的行,则结果集会包含NULL值。这对于需要展示左表所有数据的情况非常有用。MySQL中的JOIN语句有多种类型,根据需求选择合适的JOIN语句可以更加高效地查询数据。