小编典典

MySQL的。如何使用自我加入

mysql

我需要在此表上使用“自我联接”。

+------------+------+--------+
| Country    | Rank |  Year  |
+------------+------+--------+
|France      |  55  |  2000  |
+------------+------+--------+
|Canada      |  30  |  2000  |
+------------+------+--------+ 
|Liberia     |  59  |  2001  |
+------------+------+--------+ 
|Turkey      |  78  |  2000  |
+------------+------+--------+ 
|Japan       |  65  |  2003  |
+------------+------+--------+
|Romania     |  107 |  2001  |
+------------+------+--------+

我需要使用自我加入来获得与土耳其同年的国家。仅显示国家和年份。

这就是我想要做的。

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

^谷歌自我加入,并做到了。

我只得到土耳其。我究竟做错了什么?


阅读 282

收藏
2020-05-17

共1个答案

小编典典

你好亲密!

因为您说的是显示A的国家和年份,并限制了A. Country土耳其,所以您将只看到土耳其。您需要将selects更改为B.countryand
B.year或将where子句更改为B.country

这是使用交叉联接的,表中的记录越多,交叉联接的速度就会越慢。

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

可以写为…,并且可能具有相同的执行计划。

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

或这使用了INNER JOIN,它限制了引擎必须完成的工作,并且不会遭受交叉联接可能导致的性能下降。

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

为什么:

考虑一下AB发生联接时SQL引擎将做什么

+------------+------+--------+------------+------+--------+
| 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  |
+------------+------+--------+------------+------+--------+

因此,当您说展示广告A.Country以及土耳其A.Year在哪里时A.Country,您可以看到它可以返回的全部是土耳其(由于唯一的1条记录)

但是,如果您选择的B.Country是土耳其并展示A.Country,您将获得法国,加拿大和土耳其!

2020-05-17