mysql获取MAX的最后N条记录(日期)

时间:2016-04-30 18:20:44

标签: mysql sql

所以我在 product_rate_history 表中有以下数据 - enter image description here

我想选择最后N条记录(例如7条记录),通知给定产品的费率变化历史。如果产品费率每天更改超过一次,则查询应选择当天最近的费率更改。

所以从上表我想要产品ID 16 -

的输出如下
+-----------+-------------------------+------------------------+
|  product_id    |    previous_rate   |           date         |
+----------------+--------------------+------------------------|
|      16        |      2400          |   2016-04-30 23:05:35  |
|      16        |      4500          |   2016-04-29 11:02:42  |
+----------------+--------------------+------------------------+

我尝试过以下查询,但只返回一行只有最后更新率的行 -

SELECT * FROM `product_rate_history` prh
    INNER JOIN (SELECT max(created_on)  as max FROM `product_rate_history` GROUP BY Date(created_on)) prh2
      ON prh.created_on = prh2.max
    WHERE prh.product_id = 16
    GROUP BY DATE(prh.created_on)
    ORDER BY prh.created_on DESC;

1 个答案:

答案 0 :(得分:1)

首先,您不需要外部查询中的聚合。

其次,您需要在子查询中重复SELECT prh.* FROM product_rate_history prh INNER JOIN (SELECT max(created_on) as maxco FROM product_rate_history WHERE prh.product_id = 16 GROUP BY Date(created_on) ) prh2 ON prh.created_on = prh2.maxco WHERE prh.product_id = 16 ORDER BY prh.created_on DESC; 子句(对于您正在使用的方法):

struct Foo { 
    virtual void print() const {std::cout << "FOO" <<std::endl;} 
};
struct Bar : Foo { 
    void print() const {std::cout << "BAR" <<std::endl;} 
};

void slicingFunc(Foo foo){ foo.print(); }
void nonSlicingFunc(const Foo& foo) { foo.print(); }


int main() {
    Bar b;
    slicingFunc(b);    // prints FOO
    nonSlicingFunc(b); // prints BAR
    return 0;
}