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

MySql. Cómo utilizar la unión automática

¡Estás tan cerca!

Ya que dice que está mostrando el país y el año desde A y limitando por A. Country de Turquía, Turquía es todo lo que vas a ver. Debe cambiar las selecciones para que sean B.country y B.year o cambie la cláusula where para que sea B.country .

Esto está utilizando una combinación cruzada que se volverá más lenta cuantos más registros haya en una tabla.

SELECT DISTINCT b.Country, b.Year 
FROM table1 AS a, 
     table1 AS b 
WHERE a.Year=b.Year 
  and a.Country='Turkey';

podría escribirse como... y probablemente tendría el mismo plan de ejecución.

SELECT DISTINCT b.Country, b.Year 
FROM table1 AS a 
CROSS JOIN table1 AS b 
WHERE a.Year=b.Year 
  and a.Country='Turkey';

OREsto utiliza una UNIÓN INTERNA que limita el trabajo que debe hacer el motor y no sufre la degradación del rendimiento que sufriría una unión cruzada.

SELECT DISTINCT a.Country, a.Year 
FROM table1 AS a 
INNER JOIN table1 AS b 
   on a.Year=b.Year 
  and b.Country='Turkey';

POR QUÉ:

Considere lo que hará el motor SQL cuando ocurra la uniónA B

+------------+------+--------+------------+------+--------+
| A.Country  | Rank |  Year  | B.Country  | Rank |  Year  |
+------------+------+--------+------------+------+--------+
|France      |  55  |  2000  |France      |  55  |  2000  |
+------------+------+--------+------------+------+--------+
|Canada      |  30  |  2000  |France      |  55  |  2000  |
+------------+------+--------+------------+------+--------+ 
|Turkey      |  78  |  2000  |France      |  55  |  2000  |
+------------+------+--------+------------+------+--------+ 
|France      |  55  |  2000  |Canada      |  30  |  2000  |
+------------+------+--------+------------+------+--------+
|Canada      |  30  |  2000  |Canada      |  30  |  2000  |
+------------+------+--------+------------+------+--------+ 
|Turkey      |  78  |  2000  |Canada      |  30  |  2000  |
+------------+------+--------+------------+------+--------+ 
|France      |  55  |  2000  |Turkey      |  78  |  2000  |
+------------+------+--------+------------+------+--------+
|Canada      |  30  |  2000  |Turkey      |  78  |  2000  |
+------------+------+--------+------------+------+--------+ 
|Turkey      |  78  |  2000  |Turkey      |  78  |  2000  |
+------------+------+--------+------------+------+--------+ 

Así que cuando dijiste mostrar A.Country y A.Year donde A.Country es Turquía, puede ver que todo lo que puede devolver es Turquía (debido al único registro distinto)

Pero si haces B.Country es Turquía y muestra A.Country , ¡obtendrás Francia, Canadá y Turquía!