我有以下查询,它从一系列表中获取一堆列
SELECT Events.eventID, Events.eventName, Organisations.organisationName, Events.eventCrewSize, Events.eventGuestSize, Events.eventDate, Events.eventTime, Boat.boatName, Address.addressNo, Address.addressStreet, Address.addressStreetType, Address.addressSuburb, Address.addressPostCode, Address.addressState
FROM Events, Organisations, Boat, Address
WHERE Events.eventOrganisation = Organisations.organisationID AND Events.eventBoatID = Boat.boatID AND Events.eventAddressID = Address.addressID AND Events.eventDate >= CURDATE();
我的问题是,并非所有事件都具有组织,并且没有为该列返回NULL,而是没有组织就不包括任何事件。
我尝试从where子句中删除组织部分,其中包括空行,但它使用另一个事件的组织作为其值,而不是其实际的空值。
我认为这是一个联接问题,但不确定如何相应地构造它。
答案 0 :(得分:1)
您可以尝试使用左联接
SELECT Events.eventID, Events.eventName, Organisations.organisationName, Events.eventCrewSize, Events.eventGuestSize, Events.eventDate, Events.eventTime, Boat.boatName, Address.addressNo, Address.addressStreet, Address.addressStreetType, Address.addressSuburb, Address.addressPostCode, Address.addressState
FROM Events
LEFT JOIN Organisations on Events.eventOrganisation = Organisations.organisationID
LEFT JOIN Boat on Events.eventBoatID = Boat.boatID
LEFT JOIN Address on Events.eventAddressID = Address.addressID
WHERE Events.eventDate >= CURDATE();
不要忘记在主键和外键/规范化之间应用关系。您可以使用NULLIF()
来避免空值