MySQL join查询(内连接,外连接,左连接,右连接)

JOIN查询是关系型数据库的基本功能,MySQL提供多种JOIN关联查询方式,包括内连接,左连接,右连接等等,本文将简单介绍MySQL JOIN查询的分类,基本语法和使用案例。

在MySQL中,JOIN可以分为内连接和外连接,外连接又可以分为左连接和右连接。

  • join内连接
  • join外连接
    • join左连接
    • join右连接

下面将通过案例对内连接,左连接和右连接的使用进行说明。案例数据如下:

mysql> select * from t_a;
+------+--------+
| id_a | name_a |
+------+--------+
|    1 | a_1    |
|    2 | a_2    |
|    3 | a_3    |
+------+--------+
3 rows in set (0.01 sec)

mysql> select * from t_b;
+------+--------+
| id_b | name_b |
+------+--------+
|    2 | b_2    |
|    3 | b_3    |
|    4 | b_4    |
+------+--------+
3 rows in set (0.00 sec)

1. join内连接

在MySQL中,下面3个内连接join在语法上是完全相等的。注意在标准SQL中,INNER JOIN与CROSS JOIN并不等同。

  • JOIN
  • CROSS JOIN
  • INNER JOIN

内联JOIN有多种写法,以下查询结果相同。

// 没有使用join关键字
select * from t_a, t_b where t_a.id_a=t_b.id_b;

// join where
select * from t_a join t_b where t_a.id_a=t_b.id_b;

// join on
select * from t_a join t_b on t_a.id_a=t_b.id_b;

// inner join on
select * from t_a inner join t_b on t_a.id_a=t_b.id_b;

// cross join on
select * from t_a cross join t_b on t_a.id_a=t_b.id_b;

// cross join where
select * from t_a cross join t_b where t_a.id_a=t_b.id_b;

执行结果如下:

mysql> select * from t_a inner join t_b on t_a.id_a=t_b.id_b;
+------+--------+------+--------+
| id_a | name_a | id_b | name_b |
+------+--------+------+--------+
|    2 | a_2    |    2 | b_2    |
|    3 | a_3    |    3 | b_3    |
+------+--------+------+--------+
2 rows in set (0.01 sec)

2. left join 左连接

左连接join,以左边表的连接字段,依次匹配右边表,如果在右侧的表没有记录匹配上,则右则表的记录值以NULL填充。

left join示例如下:

mysql> select * from t_a left join t_b on t_a.id_a=t_b.id_b;
+------+--------+------+--------+
| id_a | name_a | id_b | name_b |
+------+--------+------+--------+
|    2 | a_2    |    2 | b_2    |
|    3 | a_3    |    3 | b_3    |
|    1 | a_1    | NULL | NULL   |
+------+--------+------+--------+
3 rows in set (0.00 sec)

3. right join 右连接

右连接join,以右边表的连接字段,依次匹配左边表,如果在左侧的表没有记录匹配上,则左则表的记录值以NULL填充。

right join示例如下:

mysql> select * from t_a right join t_b on t_a.id_a=t_b.id_b;
+------+--------+------+--------+
| id_a | name_a | id_b | name_b |
+------+--------+------+--------+
|    2 | a_2    |    2 | b_2    |
|    3 | a_3    |    3 | b_3    |
| NULL | NULL   |    4 | b_4    |
+------+--------+------+--------+
3 rows in set (0.00 sec)

文章评论

0条评论