Distinct most recent data from database

故事扮演 提交于 2019-12-01 21:54:32

You should GROUP BY all fields you want to select, no only one. This article explain the issue: https://www.psce.com/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/

The proper SQL query in this case would be:

SELECT id, upload_month, created_at
  FROM uplodaded_file
  JOIN (SELECT upload_month, MAX(created_at) created_at
          FROM uplodaded_file
      GROUP BY upload_month) months
    ON upload_month = months.upload_month
   AND created_at = months.created_at

The eloquent version of this is a little bit tricky. It will be better to use a raw query in this case.

You should use the latest() method instead of orderBy:

UploadedFile::latest()->distinct()->get();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!