doufu7464 2017-06-04 08:50
浏览 316
已采纳

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

I have a table like this:

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

I want to group by product_id and get only one latest product for each product_id. I also have a min and max price variable which should be applied to the price column.

the result of my query should be:

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

Is it possible by SQL or I should use application side?

  • 写回答

2条回答 默认 最新

  • dongrui6787 2017-06-04 09:00
    关注

    If you want to order results by date, just use orderBy():

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

    Or it's shortcuts latest() and oldest():

    Model::latest('date_column')->...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试