【问题标题】:Get LAST price per category in mysql [duplicate]在mysql中获取每个类别的最新价格[重复]
【发布时间】:2021-04-14 10:03:05
【问题描述】:

我有 1 张桌子,我想获得每个 productId 的最后支付价格 - 我该怎么做?

样品 tb1:

id    price   category
1     $5      a 
2     $7      a
3     $3      b
4     $1      b

这就是想法 => SELECT price WHERE id = ? GROUP BY category

如果您有任何想法,请告诉我;)

【问题讨论】:

  • “最后价格”是指id最大的那个吗?
  • 与问题无关,但我不会将货币类型存储在数据库中。只需使用整数并在应用程序中添加货币。
  • Stack Overflow 上几乎每天都会问这个问题。

标签: mysql sql group-by subquery greatest-n-per-group


【解决方案1】:

你可以使用not exists如下:

select t.*
  from t
 where not exists 
       (Select 1 from t tt
         Where t.id = tt.id  
           And tt.category > t.category);

【讨论】:

    【解决方案2】:

    您可以使用相关子查询,假设 id 定义了您所说的“最后一个”:

    select t.*
    from t
    where t.id = (select max(t2.id) from t t2 where t2.category = t.category);
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多