简体   繁体   English

内部联接与右表的空结果

[英]inner join with empty result from right table

I have 2 tables, restaurants and orders, each restaurant can have many orders 我有2个餐桌,餐厅和订单,每个餐厅可以有很多订单

restaurants table
id
name


orders table
id
restaurant_id
date

I need to find the restaurants that have no orders on some date range. 我需要找到在某个日期范围内没有订单的餐馆。 In orders table I save the order dates like - each row represents one day. 在订单表中,我保存订单日期,例如 - 每行代表一天。 So, I need to make inner join, but with no results from the orders table. 所以,我需要进行内连接,但没有来自orders表的结果。 Say, I need to find restaurants that are free from 2013-08-09 to 2013-08-11 date range. 说,我需要找到2013-08-09 to 2013-08-11日期范围内免费的餐馆。 How can I achieve this ? 我怎样才能做到这一点? How to make a query, that will give the restaurants with no matching in the orders table - according to the date range ? 如何根据日期范围进行查询,这将使订单表中的餐馆没有匹配?

Actually I can do it saving all the dates in the orders table with status not_ordered, and make inner join with not_ordered = true condition, but in that case I will have to populate all the table with the dates, which is not a good thing in my case. 实际上我可以保存订单表中状态为not_ordered的所有日期,并使用not_ordered = true条件进行内部not_ordered = true ,但在这种情况下,我将不得不用日期填充所有表,这不是一件好事。我的情况。

Thanks 谢谢

select r.*
from restaurant r
left join orders o on r.id = o.restaurant_id and o.date between '...' and '...'
where o.id is null;

Or you can do it using not exists as shown in other answers. 或者您可以使用not exists ,如其他答案中所示。

You don't want to use an inner join for this. 您不希望为此使用内部联接。 You can do it with an outer join, or with NOT EXISTS and a sub-query. 您可以使用外部联接,或使用NOT EXISTS和子查询来执行此操作。

Here's an example of the latter approach: 以下是后一种方法的示例:

select r.id,r.name 
from restaurants r 
where not exists (
  select NULL
  from orders o 
  where o.restaurant_id = r.id 
  and o.date >= '2013-08-09'
  and o.date <= '2013-08-11'
);

I don't know mysql very well, but this should work as general SQL: 我不太了解mysql,但这应该作为一般SQL工作:

SELECT * 
FROM restaurants 
WHERE NOT EXISTS(SELECT 1 
                 FROM order 
                 WHERE restaurant_id=id AND 
                       date BETWEEN '2013-08-09' AND '2013-08-11')

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

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