使用用户定义的var来存储max(date),然后在having子句中使用它

问题描述 投票:0回答:1

我只需要获得特定产品的最新价格变动。

  • 我返回了按产品名称分组的特定产品的所有价格变动记录
  • 我在用户定义的var中保存了价格变化的最大日期
  • 我将存储价格变化日期的字段与having子句中的var进行比较,以获得最新的价格变化

但我只返回了0行

         SELECT  
            pr.product_id
            ,pr.price set_price
            ,pr.start_date -- the timestamp of price change
            ,date(max(pr.start_date))
            ,@'max_change' := max(pr.start_date)

        FROM prices pr

        where product_id in ( -- get the id's of specific products
                            ....                
            )

        group by pr.product_id

        having date(pr.start_date) = date(@max_change)
mysql mariadb aggregate var
1个回答
2
投票

例如,您可以使用相关的子查询

drop table if exists member_token;
create Table member_token
(memberProfileId  int,createdAt date);

insert into member_token values
(1,'2019-01-01'),(1,'2019-01-01'),
(2,'2019-01-01'),(3,'2019-01-01'),
(1,'2019-01-02'),(2,'2019-01-02'),
(1,'2019-01-04'),(3,'2019-01-04');


select mt.*
from member_token mt
where createdat = 
(
select max(createdat)
from member_token mt1
where mt.memberprofileid = mt1.memberprofileid) 
order by memberprofileid
;

+-----------------+------------+
| memberProfileId | createdAt  |
+-----------------+------------+
|               1 | 2019-01-04 |
|               2 | 2019-01-02 |
|               3 | 2019-01-04 |
+-----------------+------------+
3 rows in set (0.00 sec)
© www.soinside.com 2019 - 2024. All rights reserved.