所以,我有这个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_availability
中day
的行没有等于3,所以它什么都不返回。但我希望mysql
返回NULL
字段为day
字段的行 - 因为我认为这是left join
实际执行的操作。好像我错了。
有什么想法吗?
答案 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。