我正在使用 laravel 5,我有一个关于 SQL 的问题 有一个表记录员工的职能变化。
我只需要最新的功能,所以我想使用“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();
感谢您的帮助
最佳答案
好的。您只需要知道与具有最大日期的行相对应的行。 纯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/