MySQL数据库,内连接外连接中做条件筛选和WHERE中条件筛选的区别

Posted 默慊$

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL数据库,内连接外连接中做条件筛选和WHERE中条件筛选的区别相关的知识,希望对你有一定的参考价值。

最近写数据库SQL做连接、条件筛选数据操作时发现了一个问题,就是两张表在做等值连接、或者外连接时用AND对连接表数据进行筛选和最后用WHERE对结果集数据表进行筛选得到的查询结果是有区别的。

先来个简单例子看下,在对结果进行具体分析。

1.外连接

ON后用AND对连接表数据进行筛选

WITH table_1 AS(
    SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
    UNION ALL
    SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
    UNION ALL
    SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
    UNION ALL
    SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
    SELECT 'b1' AS id_2, 'aa' AS name_2
    UNION ALL
    SELECT 'b2' AS id_2, 'bb' AS name_2
)

SELECT
    *
FROM
    table_1
LEFT OUTER JOIN table_2
ON table_1.id_2 = table_2.id_2
AND table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果

修改成WHERE对结果数据集筛选

WITH table_1 AS(
    SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
    UNION ALL
    SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
    UNION ALL
    SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
    UNION ALL
    SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
    SELECT 'b1' AS id_2, 'aa' AS name_2
    UNION ALL
    SELECT 'b2' AS id_2, 'bb' AS name_2
)

SELECT
    *
FROM
    table_1
LEFT OUTER JOIN table_2
ON table_1.id_2 = table_2.id_2
WHERE table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果

2.等值连接

ON后用AND对连接表数据进行筛选

WITH table_1 AS(
    SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
    UNION ALL
    SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
    UNION ALL
    SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
    UNION ALL
    SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
    SELECT 'b1' AS id_2, 'aa' AS name_2
    UNION ALL
    SELECT 'b2' AS id_2, 'bb' AS name_2
)

SELECT
    *
FROM
    table_1
INNER JOIN table_2
ON table_1.id_2 = table_2.id_2
AND table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果


修改成WHERE对结果数据集筛选

WITH table_1 AS(
    SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
    UNION ALL
    SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
    UNION ALL
    SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
    UNION ALL
    SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
    SELECT 'b1' AS id_2, 'aa' AS name_2
    UNION ALL
    SELECT 'b2' AS id_2, 'bb' AS name_2
)

SELECT
    *
FROM
    table_1
INNER JOIN table_2
ON table_1.id_2 = table_2.id_2
WHERE table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果

原理:在等值连接、外连接ON后用AND做条件筛选数据时,是先对连接表的数据进行条件筛选,筛选后和被连接表进行相应连接,而WHERE是对结果集进行筛选,先连接后筛选数据。

以上是关于MySQL数据库,内连接外连接中做条件筛选和WHERE中条件筛选的区别的主要内容,如果未能解决你的问题,请参考以下文章

左外连接与右外连接区别?

lyt经典版MySQL基础——进阶6:连接查询-sql99语法-内连接外连接交叉连接

Mysql连表查询

MySQL连接查询 内连接和外连接的区别

MySQL 表的内连和外连

SQL的四种连接-左外连接右外连接内连接全连接