我正在尝试了解 SQL 自联接。我有下表“人员”,其中包含员工的名字、姓氏、地址和城市(来源 W3Schools):
mysql> select * from persons;
+------+-----------+-----------+--------------+-----------+
| P_id | LastName | FirstName | Address | City |
+------+-----------+-----------+--------------+-----------+
| 1 | Hansen | Ola | Timoteivn 10 | Sandnes |
| 2 | Svendson | Tove | Borgvn 23 | Sandnes |
| 3 | Pettersen | Kari | Storgt 20 | Stavanger |
+------+-----------+-----------+--------------+-----------+
我现在想返回与“Hansen Ola”具有相同城市的员工姓名。所以我写了一个自加入,它工作正常:
mysql> select p1.Lastname, p1.firstname from persons p1, persons p2 where p1.city = p2.city and p2.lastname = 'Hansen';
+----------+-----------+
| Lastname | firstname |
+----------+-----------+
| Hansen | Ola |
| Svendson | Tove |
+----------+-----------+
但是,如果我将别名 p2 更改为 p1 即 p2.lastname = 'Hansen' 到 p1.lastname = 'Hansen',那么我不会得到两个员工的姓名。
mysql> select p1.Lastname, p1.firstname from persons p1, persons p2 where p1.city = p2.city and p1.lastname = 'Hansen';
+----------+-----------+
| Lastname | firstname |
+----------+-----------+
| Hansen | Ola |
| Hansen | Ola |
+----------+-----------+
有人可以帮我理解为什么将别名从 p2 更改为 p1 会改变结果吗?谢谢你。