MySql自连接子内连接返回交叉连接

时间:2015-07-22 00:19:03

标签: mysql sql join

我有一张叫做employeesee的桌子(三人小组):

+------------+------------+---------------+--------------+
| employeeid | lastname   | country       | departmentid |
+------------+------------+---------------+--------------+
|        123 | Rafferty   | Australia     |           31 |
|        124 | Jones      | Australia     |           33 |
|        145 | Heisenberg | Australia     |           33 |
|        201 | Robinson   | United States |           34 |
|        305 | Smith      | Germany       |           34 |
|        306 | Williams   | Germany       |         NULL |
+------------+------------+---------------+--------------+

我的意图是在同一个国家内配对(自我加入)人并将它们并排放置。

所以我在同事的帮助下提出了以下问题:

SELECT f.employeeid, f.lastname, s.employeeid, s.lastname, f.country
FROM employeee f INNER JOIN employeee s ON f.country = s.country

结果不是我想要的100%。交叉连接似乎在结果中:

+------------+------------+------------+------------+---------------+
| employeeid | lastname   | employeeid | lastname   | country       |
+------------+------------+------------+------------+---------------+
|        123 | Rafferty   |        123 | Rafferty   | Australia     |
|        124 | Jones      |        123 | Rafferty   | Australia     |
|        145 | Heisenberg |        123 | Rafferty   | Australia     |
|        123 | Rafferty   |        124 | Jones      | Australia     |
|        124 | Jones      |        124 | Jones      | Australia     |
|        145 | Heisenberg |        124 | Jones      | Australia     |
|        123 | Rafferty   |        145 | Heisenberg | Australia     |
|        124 | Jones      |        145 | Heisenberg | Australia     |
|        145 | Heisenberg |        145 | Heisenberg | Australia     |
|        201 | Robinson   |        201 | Robinson   | United States |
|        305 | Smith      |        305 | Smith      | Germany       |
|        306 | Williams   |        305 | Smith      | Germany       |
|        305 | Smith      |        306 | Williams   | Germany       |
|        306 | Williams   |        306 | Williams   | Germany       |
+------------+------------+------------+------------+---------------+

另外,为什么在AS时没有使用f.employeeid, s.employeeid alias关键字?我认为这些是必需的。

1 个答案:

答案 0 :(得分:2)

如果您只想在一个国家/地区内拥有唯一的一对人,并且您希望避免将他们与自己配对,请在查询中添加以下条件

WHERE f.employeeid < s.employeeid