简体   繁体   English

如何选择最新数据?

[英]how to select the latest data?

I am using laravel 5, and I have a question for the SQL there is the table that record the function change of employee. 我正在使用laravel 5,我对SQL有一个疑问,该表格记录了员工的职能变更。

在此处输入图片说明

I just need the latest function so I wonder to use the "group by". 我只需要最新的功能,所以我想使用“分组依据”。 but even I get the latest date, I could not get the corresponding data . 但是,即使我获得了最新日期,也无法获得相应的数据。

The most close to what I want is like this 最接近我想要的是这样的

 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();

在此处输入图片说明

Thanks for your help 谢谢你的帮助

You can select all employees with their current function with this SQL query: 您可以通过此SQL查询选择具有当前功能的所有员工:

SELECT 
    function_history.*
FROM
    function_history,
    (
        SELECT
            MAX(function_change_date) as last_change_date,
            CUID
        FROM
            function_history
        GROUP BY
            CUID
        ORDER BY function_change_date DESC
    ) tmp
WHERE
    function_history.CUID = tmp.CUID
    AND
    function_history.function_change_date = tmp.last_change_date

Ok. 好。 You just need to know the rows that corresponds to rows with max date. 您只需要知道与具有最大日期的行相对应的行。 Pure sql query: 纯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 query: 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();

I'm not sure why you're building a raw SQL query, and grouping. 我不确定为什么要构建原始SQL查询和分组。 If you just want the latest function changes for a particular CUID , then select data and order by the date: 如果您只想更改特定CUID的最新功能,请按日期选择数据和顺序:

DB::table('function_history')
    ->where('CUID', '=', $cuid)
    ->orderBy('function_change_date')
    ->get();
Please use below query and convert into laravel format
SELECT 
  `CUID`,
  MAX(`function_change_date`) AS timechange,
  (SELECT 
    `id_function` 
  FROM
    `function_history` fc 
  WHERE fc.function_change_date = MAX(f.`function_change_date`)) AS id_function 
FROM
  `function_history` f 
GROUP BY CUID ;

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

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