0

所以,我有这个 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但我希望用字段值mysql返回这一行- 因为我认为这实际上是这样做的。好像我错了。 有任何想法吗?NULLdayleft join

4

1 回答 1

1

我认为您需要将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。

于 2013-05-15T13:37:14.877 回答