mysql左右怎么连接
时间 : 2023-07-31 01:19:01声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

在MySQL数据库中,使用LEFT JOIN和RIGHT JOIN可以实现左连接和右连接。左连接返回左表中的所有记录,同时返回右表中与左表的记录相关联的记录。右连接与左连接类似,只是返回右表中的所有记录,同时返回左表中与右表的记录相关联的记录。

左连接(LEFT JOIN)使用语法如下:

SELECT * FROM 左表名 LEFT JOIN 右表名 ON 条件;

右连接(RIGHT JOIN)使用语法如下:

SELECT * FROM 左表名 RIGHT JOIN 右表名 ON 条件;

下面是一个示例,使用两个表student和score进行左连接和右连接的实例:

-- 创建student表

CREATE TABLE student (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT

);

-- 创建score表

CREATE TABLE score (

student_id INT,

course VARCHAR(50),

score INT

);

-- 插入数据

INSERT INTO student (id, name, age) VALUES (1, 'Tom', 18);

INSERT INTO student (id, name, age) VALUES (2, 'Jerry', 20);

INSERT INTO student (id, name, age) VALUES (3, 'Alice', 22);

INSERT INTO score (student_id, course, score) VALUES (1, 'Math', 80);

INSERT INTO score (student_id, course, score) VALUES (2, 'Math', 90);

INSERT INTO score (student_id, course, score) VALUES (3, 'Math', 85);

INSERT INTO score (student_id, course, score) VALUES (3, 'English', 95);

-- 左连接

SELECT student.id, student.name, score.course, score.score

FROM student LEFT JOIN score ON student.id = score.student_id;

-- 右连接

SELECT student.id, student.name, score.course, score.score

FROM student RIGHT JOIN score ON student.id = score.student_id;

执行上述代码后,可以得到左连接和右连接的结果。左连接结果如下:

+------+-------+---------+-------+

| id | name | course | score |

+------+-------+---------+-------+

| 1 | Tom | Math | 80 |

| 2 | Jerry | Math | 90 |

| 3 | Alice | Math | 85 |

| 3 | Alice | English | 95 |

+------+-------+---------+-------+

右连接结果如下:

+------+-------+---------+-------+

| id | name | course | score |

+------+-------+---------+-------+

| 1 | Tom | Math | 80 |

| 2 | Jerry | Math | 90 |

| 3 | Alice | Math | 85 |

| NULL | NULL | English | 95 |

+------+-------+---------+-------+

通过使用左连接和右连接,我们可以根据需要查询相关联表中的数据,实现更加灵活的数据查询。