自然连接和内部连接之间的区别是什么?


当前回答

自然连接只是一种避免输入的快捷方式,假设连接是简单的,并且匹配相同名称的字段。

SELECT
  *
FROM
  table1
NATURAL JOIN
  table2
    -- implicitly uses `room_number` to join

和……一样。

SELECT
  *
FROM
  table1
INNER JOIN
  table2
    ON table1.room_number = table2.room_number

然而,你不能用快捷格式做的是更复杂的连接…

SELECT
  *
FROM
  table1
INNER JOIN
  table2
    ON (table1.room_number = table2.room_number)
    OR (table1.room_number IS NULL AND table2.room_number IS NULL)

其他回答

内联接,联接两个列名相同的表。

自然连接,连接两个列名和数据类型相同的表。

内部连接是这样一种连接,即连接表中的匹配行对于返回的第一个表中的一行是必需的 外部连接是这样一种连接,即对于返回的第一个表中的一行,已连接表中的匹配行不需要 自然连接是一种连接(可以是自然左连接,也可以是自然右连接),它假设连接条件是两个表中同名列匹配的位置

我会避免像使用瘟疫一样使用自然连接,因为自然连接是:

not standard sql [SQL 92] and therefore not portable, not particularly readable (by most SQL coders) and possibly not supported by various tools/libraries not informative; you can't tell what columns are being joined on without referring to the schema your join conditions are invisibly vulnerable to schema changes - if there are multiple natural join columns and one such column is removed from a table, the query will still execute, but probably not correctly and this change in behaviour will be silent hardly worth the effort; you're only saving about 10 seconds of typing

自然连接:它是两个表中所有列的组合或组合结果。 它将返回第一个表相对于第二个表的所有行。

内部连接:这种连接将工作,除非任何列名将在两个表中same

内连接和自然连接基本相同,但有细微的区别。不同的是,在自然连接中不需要指定条件,但在内部连接中条件是必须的。如果我们在内连接中指定条件,则生成的表就像笛卡尔积。

mysql> SELECT  * FROM tb1 ;
+----+------+
| id | num  |
+----+------+
|  6 |   60 |
|  7 |   70 |
|  8 |   80 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

mysql> SELECT  * FROM tb2 ;
+----+------+
| id | num  |
+----+------+
|  4 |   40 |
|  5 |   50 |
|  9 |   90 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

内连接:

mysql> SELECT  * FROM tb1 JOIN tb2 ; 
+----+------+----+------+
| id | num  | id | num  |
+----+------+----+------+
|  6 |   60 |  4 |   40 |
|  7 |   70 |  4 |   40 |
|  8 |   80 |  4 |   40 |
|  1 |    1 |  4 |   40 |
|  2 |    2 |  4 |   40 |
|  3 |    3 |  4 |   40 |
|  6 |   60 |  5 |   50 |
|  7 |   70 |  5 |   50 |
|  8 |   80 |  5 |   50 |
.......more......
return 36 rows in set (0.01 sec) 
AND NATURAL JOIN :

    mysql> SELECT  * FROM tb1 NATURAL JOIN tb2 ;
    +----+------+
    | id | num  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    |  3 |    3 |
    +----+------+
    3 rows in set (0.01 sec)