sql >> Base de Datos >  >> RDS >> Mysql

¿Cuándo usar LEFT JOIN y cuándo usar INNER JOIN?

¿Hay alguna trampa? Sí, las uniones izquierdas son una forma de unión externa, mientras que las uniones internas son una forma de unión interna.

Aquí hay ejemplos que muestran la diferencia. Empezaremos con los datos base:

mysql> select * from j1;
+----+------------+
| id | thing      |
+----+------------+
|  1 | hi         |
|  2 | hello      |
|  3 | guten tag  |
|  4 | ciao       |
|  5 | buongiorno |
+----+------------+

mysql> select * from j2;
+----+-----------+
| id | thing     |
+----+-----------+
|  1 | bye       |
|  3 | tschau    |
|  4 | au revoir |
|  6 | so long   |
|  7 | tschuessi |
+----+-----------+

Y aquí veremos la diferencia entre una combinación interna y una combinación izquierda:

mysql> select * from j1 inner join j2 on j1.id = j2.id;
+----+-----------+----+-----------+
| id | thing     | id | thing     |
+----+-----------+----+-----------+
|  1 | hi        |  1 | bye       |
|  3 | guten tag |  3 | tschau    |
|  4 | ciao      |  4 | au revoir |
+----+-----------+----+-----------+

Hmm, 3 filas.

mysql> select * from j1 left join j2 on j1.id = j2.id;
+----+------------+------+-----------+
| id | thing      | id   | thing     |
+----+------------+------+-----------+
|  1 | hi         |    1 | bye       |
|  2 | hello      | NULL | NULL      |
|  3 | guten tag  |    3 | tschau    |
|  4 | ciao       |    4 | au revoir |
|  5 | buongiorno | NULL | NULL      |
+----+------------+------+-----------+

¡Vaya, 5 filas! ¿Qué pasó?

Uniones externas como left join preservar las filas que no coinciden, por lo que la consulta de combinación izquierda conserva las filas con id 2 y 5. Las columnas restantes se completan con NULL.

En otras palabras, las uniones izquierda e interior no son intercambiables.