我最近发现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”会完成什么?这怎么会影响加入?
解决方法
如果人员表是:
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(在管理器表上)连接.如果管理器表中存在相同的id,则会发生另外一个连接.