问题描述
如果人员表是:
id name
1 Person One
2 Person Two
3 Person Three
4 Person Four
5 Person Five
如果经理表是
id name
-1 Admin
2 Manager One
3 Manager Two
如果查询是:
SELECT disTINCT *
FROM Person LEFT JOIN Manager
ON (Manager.id = Person.id OR Manager.id = -1)
那么结果是:
Person One -1 Admin
Person Two -1 Admin
Person Two 2 Manager One
Person Three -1 Admin
Person Three 3 Manager Two
Person Four -1 Admin
Person Five -1 Admin
在这里,所有人员行都以-1 Admin(在manager表上)联接,并且如果manager表中存在相同的ID,则会再发生一次联接。
解决方法
我最近发现,LEFT JOIN的ON子句可能包含诸如(1 = 1)的值。
这让我很沮丧,因为它破坏了我对联接功能的理解。
我遇到了以下情况的详细版本:
SELECT DISTINCT Person.ID,...
FROM Person LEFT JOIN Manager
ON (Manager.ID = Person.ID OR Manager.ID = -1))
WHERE (...)
这是完全合法的。如果有的话,“ Manager.ID = -1”会完成什么工作?这如何影响Join?