postgreSQL-为给定列提取最新的1条记录



我有以下查询,它可以很好地提取厨师、他们的菜单和他们出售的食物的信息。

然而,它缺少最后一列;last_order_placed";

该列需要从表"中提取单个最新(最近(条目;订单";,列名";放置";。每一家特定的商店(store.id(都会有一个订单价值。每次食品销售时都会添加。

这是一个postgresql13数据库。

我想添加一列,包括orders中的最新条目。为每个商店(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 on:

select distinct on (store_id) . . .
. . .
order by store_id, o.placed desc

你可能不需要group by。至少,你的问题并不能解释为什么这是必要的。

最新更新