我的桌子很少。
类别
项目
restaurant_items
饭店
new_sponsoreds
地区
如果我简要解释这些表格,categories
是食物类别。例如:-蛋糕item
就像是食物的子类别。例如:-巧克力蛋糕。restaurant_items
是属于特定餐厅的项目的实例。例如:-ABC餐厅的巧克力蛋糕。restaurants
顾名思义就是一家餐厅,而regions
是restaurant
所在的区域。
最重要的一项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_items
和region
的所有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_id
和restaurant_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