sql - 如何选择最新的数据?

标签 sql laravel

我正在使用 laravel 5,我有一个关于 SQL 的问题 有一个表记录员工的职能变化。

enter image description here

我只需要最新的功能,所以我想使用“group by”。 但即使我得到了最新日期,我也无法得到相应的数据。

最接近我想要的就是这样

 DB::table('function_history')
->select(DB::raw('id_history,function_history.CUID,
              max(function_change_date)as time, id_function'))
   ->orderBy('time','desc') ->groupBy('CUID')->get();

enter image description here

感谢您的帮助

最佳答案

好的。您只需要知道与具有最大日期的行相对应的行。 纯sql查询:

select 
    id_history, CUID, id_function, function_change_date
from 
    function_history t1 
    join 
    (select max(function_change_date) as maxdt from function_history group by CUID) t2 on t1.function_change_date = t2.maxdt

Laravel 查询:

DB::table('function_history')->select('id_history', 'CUID', 'id_function', 'function_change_date')
            ->join(DB::raw('(select max(function_change_date) as maxdt from function_history group by CUID) temp'),
                'temp.maxdt', '=', 'date'
            )->get();

关于sql - 如何选择最新的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775979/

相关文章:

laravel - 调用未定义的方法 Illuminate\Database\Eloquent\Builder::sortByDesc()

php - Ajax 代码无响应

php - 尝试将键值插入 MySQL 表时出错

sql - 使用 select 插入来自另一个 select 的列值

mysql - 三个表的总和(金额)返回 null

php - Laravel maatwebsite excel包导入2000+行导致1390代码错误

sql - 选择除某些 PostgreSQL 之外的所有列

mysql - Laravel 查询在日期时间列上使用 yyyy-mm--dd 值

php - 如何在使用 eloquent 时排除某些列

php - Laravel 5,子域路由,带可选参数