mysql在同一个查询中有一个左连接和几个内部连接

dy2hfwbg  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(332)

我没有几张table。
类别
项目
餐厅物品
餐厅
新赞助商
区域
如果我简单解释一下这些表格, categories 是食品类。例如:蛋糕 item 就像食物的一个子类。例:巧克力蛋糕。 restaurant_items 是属于特定餐厅的项的示例。例:餐厅的巧克力蛋糕。 restaurants 顾名思义就是一家餐厅 regions 是一个 restaurant 位于。
最重要的一个新赞助商是餐馆把他们的食物作为广告来宣传。

runday    | category_id | restaurant_id

2018-12-5 | 23          | 45

这个 new_sponsoreds 表指示,我们需要在上运行广告 restaurant_items 哪里 category_id 餐厅里的23号是45号。
我的用例
获取所有 restaurant_items 从给定的 region 然后过滤这些 restaurant_items 通过 category 最后右外接这个结果 new_sponsoreds .
这样一个食品应用程序用户就可以 restaurant_itemsregion (纽约)并用 category (蛋糕)。
此查询用于获取 restaurant_items .

SELECT restaurant_items.* FROM test2.restaurant_items
inner join items on restaurant_items.item_id = items.Item_id
inner join categories on items.category_id = categories.id
inner join restaurants on restaurant_items.restaurant_id = restaurants.Restaurant_id
where restaurants.region_id = 7 and categories.id = 33

这个很好用。但是当我试图把这个结果和 new_sponsoreds 像这样的table,

SELECT restaurant_items.*,new_sponsoreds.* FROM test2.restaurant_items
inner join items on restaurant_items.item_id = items.Item_id
inner join categories on items.category_id = categories.id
inner join restaurants on restaurant_items.restaurant_id = restaurants.Restaurant_id
left outer join new_sponsoreds on categories.id = new_sponsoreds.category_id
where restaurants.region_id = 7 and categories.id = 33
and new_sponsoreds.runday = current_date()

此查询返回空行集。但我所期待的是这个问题会给我所有 restaurant_itemsregion 和一个 category_id 如果一家餐厅在今天推广一个类别,这也将包括结果。

id |restaurant_id | Item_id | runday    | category_id | restaurant_id
1  |12            | 23      |2018-12-04 | 25          | 12
2  |12            | 45      |null       | null        | null
3  |15            | 23      |null       | null        | null

这是我的例外结果表 restaurant_id 以及 Item_idrestaurant_items 以及其他来自 new_sponsoreds 在这里第一张唱片符合 left outer join 因为 restuarant_id 12号在那里宣传 category_id 2018年12月25日。
第二张唱片即使是同一家餐厅的,也不相配 category_id 不等于25。
第三个记录有相同的 category_id 作为第一张唱片。但它不匹配的加入,因为它属于不同的餐厅。
这是我预期的结果。但是在我将左连接部分添加到查询之后,我什么也没有得到。为什么会这样?

ikfrs5lh

ikfrs5lh1#

SELECT restaurant_items.*,new_sponsoreds.* FROM test2.restaurant_items
inner join items on restaurant_items.item_id = items.Item_id
inner join categories on items.category_id = categories.id
inner join restaurants on restaurant_items.restaurant_id = restaurants.Restaurant_id
left outer join new_sponsoreds on categories.id = new_sponsoreds.category_id
and new_sponsoreds.runday = current_date() and new_sponsoreds.restaurant_id = restaurants.Restaurant_id
where restaurants.region_id = 7 and categories.id = 33

正如注解所建议的那样,我将lat行向上移动了一行,并将此部分添加到左侧外部联接中

and new_sponsoreds.restaurant_id = restaurants.Restaurant_id

相关问题