繁体   English   中英

Laravel orderby 查询与不同

[英]Laravel orderby query with distinct

我正在尝试通过 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 因为不同的..

正确的做法是什么?

尝试使用 group by 而不是distinct

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

您可以使用 latest() 方法。

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

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

Laravel 文档中的官方文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM