【问题标题】:Not Joining Correctly未正确加入
【发布时间】:2018-11-24 05:14:13
【问题描述】:

我有以下查询,它从一系列表中获取一堆列

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 子句中删除组织部分,其中包括空行,但它使用另一个事件的组织作为其值,而不是实际的空值。

我认为这是一个连接问题,但不确定如何相应地构建它。

【问题讨论】:

  • 编写具有意外行为的最少代码并通过参考手册或教科书来解释您的期望。否则你只是要求我们重写一个。逗号进行交叉连接 & where 保留满足条件的行,如内部连接。了解联接如何工作。对于代码问题,请阅读minimal reproducible example并采取行动。

标签: mysql database join select


【解决方案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() 来避免空值

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多