【问题标题】:Laravel orderby query with distinctLaravel orderby 查询具有不同的
【发布时间】:2023-03-07 12:26:01
【问题描述】:

我正在尝试通过 desc created_time 获取具有最新订单的唯一 thread_id

这是我的表格示例。

===========================================
= id = thread_id = page_id = created_time =
===========================================
= 1  = 3         = 1       = 1551162660   =
= 2  = 1         = 1       = 1551162661   =
= 3  = 1         = 1       = 1551162662   =
= 4  = 2         = 1       = 1551162663   =
= 5  = 3         = 1       = 1551162664   =
= 6  = 1         = 1       = 1551162665   =
===========================================

这是我的代码。

DB::table('table_a')->select('thread_id')->orderBy('created_time', 'desc')->where('page_id', $page_id)->distinct()->get();

我的代码现在的问题是,它跳过了最新的 created_time 因为不同的..

正确的做法是什么?

【问题讨论】:

  • 请使用 toSql() 打印您的查询并更新您的查询。
  • DB::raw("SELECT thread_id, MAX(created_time) FROM table_a GROUP BY thread_id");

标签: php laravel sql-order-by distinct


【解决方案1】:

尝试使用 group by 而不是 distinct

DB::table('table_a')
 ->select('thread_id')
 ->orderBy('created_time', 'desc')
 ->where('page_id', $page_id)
 ->groupBy('thread_id')
 ->get();

【讨论】:

    【解决方案2】:

    你可以使用 latest() 方法。

    DB::table('table_a')->latest('created_time')->distinct()->get();
    

    编辑:如果您仍然有问题,您也可以使用 groupBy() 方法。

    Official documentation at the Laravel Docs.

    【讨论】:

    • 为您的具体问题创建一个问题,“对我不起作用”并不能解释正在发生的事情。我无法仅提供这些信息。
    • @Kerel , latest 在功能上等同于原始问题中的 orderBy 。这就是为什么它对 Pablo 不起作用。 public function latest($column = 'created_at') { return $this->orderBy($column, 'desc'); }
    • Pedro 没有发布任何内容,所以你怎么知道他想做什么?
    • 这和使用where没有什么不同,如果你使用latest,它仍然会给你同样的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2015-07-29
    • 2015-04-14
    • 1970-01-01
    • 2016-09-11
    • 2018-05-12
    相关资源
    最近更新 更多