简体   繁体   English

SQL Join Issue 一对多关系

[英]SQL Join Issue One to Many relationship

I have two tables product and reservations, I want retrieve all the products that aren't not included into a date range, I'm using a left join to reach the related reservations to a specific product, the matter is that I must filter by date range, and return all the products that aren't included in that range, there are several products, and in most of the cases the products aren't related to any reservation, I'm kinda lost with this:我有两个表产品和预订,我想检索不包含在日期范围内的所有产品,我正在使用左连接来达到特定产品的相关预订,问题是我必须过滤日期范围,并返回所有未包含在该范围内的产品,有几种产品,并且在大多数情况下,这些产品与任何预订无关,我对此有点迷茫:

select p.idProduct, p.name, p.description, p.latitude, p.longitude, p.address,
             p.qualification, p.favourite,p.idCategory,p.idCity, p.rules, p.health, p.politics,
             r.idReservation
             from product p 
            LEFT JOIN city c ON c.idCity = p.idCity 
            LEFT JOIN reservation r ON r.idProduct = p.idProduct 
            where p.idCity = 1 
            AND ( 
            (r.endDate < '2021-11-20' AND r.startDate< '2021-11-28') OR 
            (r.endDate > '2021-11-28' AND r.startDate > '2021-11-20') 
            );

In this case for example there are not reservations on those dates, but there are multiple products, that doesn't have a relationship with any reservation.例如,在这种情况下,这些日期没有预订,但是有多个产品与任何预订都没有关系。

One product could be related to zero or many reservations.一种产品可能与零个或多个预订相关。

I will appreciate any hint about it.我会很感激任何关于它的提示。

IF what do you mean (it's not so clear what do you need or your logic) is that reservation is not mandatory, then your conditions doesn't have to be mandatory.如果您的意思是(不清楚您需要什么或您的逻辑)是预订不是强制性的,那么您的条件不必是强制性的。 Move them to LEFT JOIN将它们移动到 LEFT JOIN

select p.idProduct, p.name, p.description, p.latitude, p.longitude, p.address,
             p.qualification, p.favourite,p.idCategory,p.idCity, p.rules, p.health, p.politics,
             r.idReservation
             from product p 
            LEFT JOIN city c ON c.idCity = p.idCity 
            LEFT JOIN reservation r ON r.idProduct = p.idProduct AND ( 
            (r.endDate < '2021-11-20' AND r.startDate< '2021-11-28') OR 
            (r.endDate > '2021-11-28' AND r.startDate > '2021-11-20') 
            )
            where p.idCity = 1 
            ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM