简体   繁体   English

左连接至少一行,右边是mysql的条件

[英]left join with at least one row with condition from right mysql

I have 2 tables, restaurants and orders, orders table have restaurant_id , status and date fields, each day is a separate line in orders table. 我有2个表,餐馆和订单,订单表有restaurant_idstatusdate字段,每天是订单表中的单独行。

I need to filter the restaurants and show only the restaurants that have at least one reservation for some date range, but I have to show it on a calendar, it should look like a list of restaurants with information. 我需要过滤餐馆并仅显示在某个日期范围内至少有一个预订的餐厅,但我必须在日历上显示它,它应该看起来像一个有信息的餐馆列表。

Smth like this 像这样的Smth

在此输入图像描述

So, it means that if at least one day with reserved status condition is satisfied in that date range, all the orders for that date range for that restaurant should be fetched as well. 因此,这意味着如果在该日期范围内满足at least one day with reserved status条件的日期,那么也应该获取该餐馆的该日期范围的所有订单。

I can not make a usual inner join, 我无法进行通常的内部联接,

SELECT r.`id`, r.`name`, o.`date`, o.`status`
FROM restaurants r
INNER JOIN orders o ON r.id = o.restaurant_id AND o.date BETWEEN '2013-08-10' AND '2013-08-31'
AND status = 'reserved' 

because, in this case, for example, I will not have the order information for August 31, for restaurant2, because though it is in date rage from 10 - 31, but its status is 'closed'. 因为,在这种情况下,例如,对于restaurant2,我将不会获得8月31日的订单信息,因为尽管它的日期范围为10 - 31,但其状态为“已关闭”。 So, I am thinking to make a left join like this 所以,我想这样做一个左连接

SELECT r.`id`, r.`name`, o.`date`, o.`status`,  o.`id` order_id
FROM restaurants r
LEFT JOIN orders o ON r.id = o.restaurant_id AND
o.date BETWEEN '2013-08-10' AND '2013-08-31' 
WHERE o.`id` IS NOT NULL 

But I need to also add one condition to ensure that there is at least one row with order's status = 'reserved', I tried to add where clause like COUNT(o.status = 1) > 0 but it gives an error. 但是我还需要添加一个条件来确保至少有一行具有order ='reserved',我尝试添加COUNT(o.status = 1) > 0类的where子句,但是它给出了一个错误。

THanks 谢谢

I think the best way to achieve this (assuming things like 'N/A' and 'reserved' are stored in the orders table is to join to all orders in the first instance, and then use a second join to limit it to only restaurants that have a reservation within that period: 我认为实现这一目标的最佳方法(假设订单表中存储“N / A”和“保留”之类的东西是在第一个实例中加入所有订单,然后使用第二个连接将其限制为仅限于餐馆在此期间内有预订:

SELECT  r.`id`, r.`name`, o.`date`, o.`status`,  o.`id` order_id
FROM    restaurants r
        INNER JOIN orders o 
            ON r.id = o.restaurant_id
            AND o.date BETWEEN '2013-08-10' AND '2013-08-31' 
        INNER JOIN
        (   SELECT  DISTINCT o2.Restaurant_ID
            FROM    orders o2
            WHERE   o2.date BETWEEN '2013-08-10' AND '2013-08-31' 
            AND     o2.Status = 'Reserved'
        ) o2
            ON r.id = o2.restaurant_id;

Example on SQL Fiddle 关于SQL小提琴的例子

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

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