使用多个AND条件与多个内部联接的内部联接之间的差异

时间:2017-11-12 08:02:28

标签: mysql join self-join

我是mysql的新手。我必须加入两个表

让我们称之为table_A和Table_B

我使用以下代码学习了内连接表

SELECT *
FROM table_A a 
INNER JOIN table_B b
ON a.criteria_1 = b.criteria_1
AND a.criteria_2 = b.criteria_2
AND a.criteria_3 = b.criteria_3

今天我遇到了一个使用多个内部联接的查询

SELECT *
FROM table_A a 
INNER JOIN table_B b
ON a.criteria_1 = b.criteria_1
INNER JOIN table_B b1
ON a.criteria_2 = b1.criteria_2
INNER JOIN table_B b2
ON a.criteria_3 = b3.criteria_3

这两者之间有什么区别?

这是我第一次在这里写一个问题。

1 个答案:

答案 0 :(得分:1)

差异很大,第一个查询只返回6列第二个将返回12,!st查询所有条件必须匹配第二个查询任何都可以。

DROP TABLE IF EXISTS A,B;

CREATE TABLE A (C1 INT, C2 INT, C3 INT);
CREATE TABLE B (C1 INT, C2 INT, C3 INT);

INSERT INTO A VALUES (1,1,1),(1,2,4);
INSERT INTO B VALUES (1,1,1),(1,2,3);

SELECT * FROM
A
JOIN B ON A.C1 = B.C1 AND A.C2 = B.C2 AND A.C3 = B.C3;

SELECT * 
FROM A 
JOIN B B1 ON A.C1 = B1.C1 
JOIN B B2 ON A.C2 = B2.C2 
JOIN B B3 ON A.C3 = B3.C3;

SELECT * FROM
    -> A
    -> JOIN B ON A.C1 = B.C1 AND A.C2 = B.C2 AND A.C3 = B.C3;
+------+------+------+------+------+------+
| C1   | C2   | C3   | C1   | C2   | C3   |
+------+------+------+------+------+------+
|    1 |    1 |    1 |    1 |    1 |    1 |
+------+------+------+------+------+------+
1 row in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> SELECT *
    -> FROM A
    -> JOIN B B1 ON A.C1 = B1.C1
    -> JOIN B B2 ON A.C2 = B2.C2
    -> JOIN B B3 ON A.C3 = B3.C3;
+------+------+------+------+------+------+------+------+------+------+------+------+
| C1   | C2   | C3   | C1   | C2   | C3   | C1   | C2   | C3   | C1   | C2   | C3   |
+------+------+------+------+------+------+------+------+------+------+------+------+
|    1 |    1 |    1 |    1 |    1 |    1 |    1 |    1 |    1 |    1 |    1 |    1 |
|    1 |    1 |    1 |    1 |    2 |    3 |    1 |    1 |    1 |    1 |    1 |    1 |
+------+------+------+------+------+------+------+------+------+------+------+------+
2 rows in set (0.00 sec)