连续三个左连接返回意外结果

时间:2013-05-15 12:40:15

标签: mysql sql join left-join

所以,我有这个SQL查询:

select
  o.id,
  o.name,
  d.name,
  w.day,
  o.suspended
from resource o
  left join resource d on d.vehicle_ID = o.ID
  left join week_days_availability_to_resource aw on d.ID=aw.resource_ID
  left join week_days_availability w on aw.calendar_ID=w.ID
where o.IS_DELETED <> true
      and (d.IS_DELETED is null or d.IS_DELETED <> true)
      and o.marketId = 98
      and (w.day = 3 or w.day is null)
      and (o.suspended <> true or o.id in (-1))  

它返回我需要的所有行 - 除了只有一行。表resource o中有一行与resource d结合,然后它与week_days_availability_to_resource结合(此表中有一些行resource_ID等于d.ID )。问题是week_days_availabilityday的行没有等于3,所以它什么都不返回。但我希望mysql返回NULL字段为day字段的行 - 因为我认为这是left join实际执行的操作。好像我错了。
有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我认为您需要将where条件移到on子句中。

from resource o
  left join resource d on d.vehicle_ID = o.ID
  left join week_days_availability_to_resource aw on d.ID=aw.resource_ID
  left join week_days_availability w on aw.calendar_ID=w.ID and w.day = 3
where o.IS_DELETED <> true
      and (d.IS_DELETED is null or d.IS_DELETED <> true)
      and o.marketId = 98
      and (w.day = 3 or w.day is null)
      and (o.suspended <> true or o.id in (-1)) 

问题是w.day可能等于其他一些值,比如说4.满足left join条件(如最初编写的那样),但它不符合where条件。通过将条件移动到on子句中,没有匹配,您将获得NULL。