我的桌子很少。


类别
项目
restaurant_items
饭店
new_sponsoreds
地区


如果我简要解释这些表格,

categories是食物类别。例如:-蛋糕

item就像是食物的子类别。例如:-巧克力蛋糕。

restaurant_items是属于特定餐厅的项目的实例。例如:-ABC餐厅的巧克力蛋糕。

restaurants顾名思义就是一家餐厅,而regionsrestaurant所在的区域。

最重要的一项new_sponsoreds是餐馆在广告中宣传其食品的地方。

runday    | category_id | restaurant_id

2018-12-5 | 23          | 45


new_sponsoreds表指示,我们需要在restaurant_items的餐厅ID为45的category_id为23的位置上投放广告。

我的使用情况

从给定的restaurant_items获取所有的region,然后过滤它们

通过restaurant_items进行category运算,最后将外部结果与new_sponsoreds联接。

这样,食品应用程序用户就可以从restaurant_items(纽约)获取region并通过category(CAKES)对其进行过滤。

此查询用于获取该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表结合在一起时,

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在2018-12-04提升了category_id 25。

第二条记录即使属于同一家餐厅,也不匹配,它的category_id不等于25。

第三条记录与第一条记录具有相同的category_id。但是它与联接不匹配,因为它属于另一家餐厅。

这是我的预期结果。但是将左联接部分添加到查询后,我什么也没得到。为什么会发生这种情况?

最佳答案

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


正如评论所建议的,我将纬度线向上移动一个,并将此部分添加到左侧的外部连接中

and new_sponsoreds.restaurant_id = restaurants.Restaurant_id

10-04 12:11
查看更多