如何获取按日期排序的记录

How to get one records that sorted by date

我有一个 table 这样的:

id    product_id   price      date
1       1001        100     2017-05-29
2       1005        101     2017-03-30
3       1001        102     2017-03-30
4       1003        106     2017-06-07
5       1005        106     2017-04-30

我想按 product_id 分组,每个 product_id 只得到一个最新产品。我还有一个最小和最大价格变量,应应用于 price 列。

我的查询结果应该是:

1       1001        100     2017-05-29
4       1003        106     2017-06-07
5       1005        106     2017-04-30

是否可以通过 SQL 或者我应该使用应用程序端?

如果您想按日期排序结果,只需使用 orderBy():

Model::orderBy('date_column', 'desc')->whereBetween('price', [$min, $max])->groupBy('product_id')->take(3)->get();

或者它的快捷方式 latest()oldest():

Model::latest('date_column')->...

您可以使用 subqueries。首先 select 从你的 table 按日期排序,然后用它按 product_id:

分组
SELECT * FROM (SELECT * FROM `your_table` t ORDER by date desc) as date_ordered group by product_id ORDER by id