【发布时间】:2020-10-05 15:28:20
【问题描述】:
我有以下查询,它可以很好地提取有关厨师、他们的菜单和他们出售的食品的信息。
但是,它缺少最后一列“last_order_placed”
此列需要从表“orders”中提取单个最新(最新)条目,列名“placed”。每个特定的商店 (store.id) 都会在每次销售该食品时在 orders.placed 中有一个值。
这是一个 postgresql 13 数据库。
我想添加一列以包含来自 orders.placed 的每个商店 (store.id) 的最新条目:
select distinct
account.id,
account.email,
account.firstname,
account.lastname,
account.phone,
account.zip_code,
menu.name,
kitchen_item.name,
kitchen_item.price,
kitchen_item.daily_max_orders,
menu.pickup_start_time,
menu.pickup_end_time,
menu.repeat_mon,
menu.repeat_tues,
menu.repeat_wed,
menu.repeat_thurs,
menu.repeat_fri,
menu.repeat_sat,
menu.repeat_sun,
from account
left join store on account.id = store.account_id
left join menu on store.id = menu.store_id
left join kitchen_item on store.id = kitchen_item.store_id
left join menu_item on (kitchen_item.id = menu_item.kitchen_item_id and menu.id = menu_item.menu_id)
left join orders on store.id = orders.store_id
where account.is_seller_fully_registered = True
and account.is_deleted = False
and menu.deleted = False
and menu_item.is_deleted = False
group by account.id, account.email, account.firstname, account.lastname, account.phone, account.zip_code, menu.name, kitchen_item.name, kitchen_item.price, kitchen_item.daily_max_orders, menu.pickup_start_time, menu.pickup_end_time, menu.repeat_mon, menu.repeat_tues, menu.repeat_wed, menu.repeat_thurs, menu.repeat_fri, menu.repeat_sat, menu.repeat_sun
order by account.id asc;
我不知道如何将其与所有其他联接合并。我已经尝试过其他帖子的建议,从我收集到的信息中,我应该在订单表的连接上实现这一点。 比如:
INNER JOIN (
select MAX (orders.placed) last_order
from orders o on orders.store_id = store.id
)
GROUP BY store.id
谁能帮帮我?
【问题讨论】:
-
请提供样本数据和期望的结果。尚不清楚为什么当前查询首先需要
distinct(更不用说distinct和group by充其量是多余的)。 -
注意:
and menu.deleted = False and menu_item.is_deleted = False会将这两个左连接变成普通连接。 -
感谢您的输入,不,我没有真正的理由需要使用 distinct 和 group by。提供带有一些示例数据的插入语句将是一项非常耗时的任务,但我会尽力提供。谢谢
标签: sql postgresql greatest-n-per-group