简体   繁体   English

如何更新 postgres 中某人拥有的最便宜的物品?

[英]How to update the cheapest item owned by someone in postgres?

Let's say I have the following table in Postgres:假设我在 Postgres 中有下表:

fruit

fruit_id   owner_id   fruit_price    notes
-------------------------------------------
   1          5            15         
   2          5            30
   3          5            20
   4          8            10
   5          8            80

I am looking for a way to update the cheapest fruit owned by someone.我正在寻找一种方法来更新某人拥有的最便宜的水果。

That is, I am looking for an operation that would allow me to set the notes column for the cheapest fruit owned by an individual.也就是说,我正在寻找一种操作,允许我为个人拥有的最便宜的水果设置notes列。 So this should only ever update one row (updating multiple rows is fine if there are several ties for the smallest value).因此,这应该只更新一行(如果最小值有多个关系,则更新多行就可以了)。

For example (psuedocode):例如(伪代码):

UPDATE fruit SET notes = 'wow cheap' WHERE owner_id = 5 AND fruit_price IS cheapest;

And this would update the first row in the above example data, because fruit_id of 1 is the cheapest fruit owned by user 5 .这将更新上述示例数据中的第一行,因为1fruit_id是用户5拥有的最便宜的水果。

One possible way is simply to use a correlated subquery:一种可能的方法是简单地使用相关子查询:

update fruit set
  notes = 'some notes'
where owner_id = 5
  and fruit_price = (
    select min(fruit_price) from fruit f2 
    where f2.owner_id = fruit.owner_id
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM