相当于mysql/laravel中的限定语句?

Equivalent to a qualify statement in mysql/laravel?

我有一个如下所示的数据库:

ID |   facebook_id  | likes | created_at
--------------------------------------------------
 1 |      x         | 100   | 2017-01-01 12:10:15
 2 |      x         | 110   | 2017-01-02 12:10:15
 3 |      y         | 115   | 2017-01-01 12:10:15
 4 |      y         | 120   | 2017-01-02 12:10:15
 5 |      z         | 200   | 2017-01-01 12:10:15
 6 |      z         | 201   | 2017-01-01 12:10:15
 7 |      z         | 200   | 2017-02-02 12:10:15
 8 |      z         | 205   | 2017-02-03 12:10:15
 9 |      z         | 250   | 2017-03-04 12:10:15

我想获取 table 中每个唯一 facebook_id 的最新记录,然后按 likesdescending 顺序排序。我正在使用 laravel 5.4 and mysql for the database. In teradata 我会做类似

的事情
QUALIFY ROW_NUMBER() OVER(PARTITION BY facebook_id ORDER BY created_at DESC) = 1

facebook_id 对结果进行排序,并按唯一性 facebook_id 获取最新行。但我不确定如何在 laravel/mysql.

中执行此操作

我试过了

Database::select('facebook_id', 'likes', 'created_at')
          ->orderBy('likes', 'desc')
          ->distinct('facebook_id')
          ->latest('created_at')
          ->limit(20)
          ->get();

但它只是按 likes 排序,并没有让我独一无二 facebook_id's

我的结果是:

Top Profile ID: z Likes:250
Top Profile ID: z Likes:205
Top Profile ID: z Likes:201
Top Profile ID: z Likes:200

我想得到的是:

Top Profile ID: z Likes:250
Top Profile ID: y Likes:120
Top Profile ID: x Likes:110

本题:

I want to get the latest record for each of the unique facebook_id's in the table then order it by likes in descending order.

有答案。有多种方法。这是一个:

select t.*
from t
where t.created_at = (select max(t2.create_at)
                      from t t2
                      where t2.facebook_id = t.facebook_id
                     )
order by t.likes desc;

我认为您只需要在 facebook_id 上查询 groupBy

->groupBy('facebook_id')