如何在yii2查询中使用MAX函数?

时间:2017-05-24 07:47:13

标签: mysql yii2 yii2-advanced-app

我有一个问题:

    SELECT hs.*
    FROM hire_screening hs
    INNER JOIN
    (SELECT resume_id, MAX(created_date) AS MaxDateTime
    FROM hire_screening
    GROUP BY resume_id) hire_screening 
    ON hs.resume_id = hire_screening.resume_id 
    AND hs.created_date = hire_screening.MaxDateTime

这是我的表:

enter image description here

我需要这样的答案:

enter image description here

我试过了:

    $query = HireScreening::find()-
             ->select(["hire_screening.screening_id","hs.resume_id",
            "MAX(hs.created_date) AS 
             MaxDateTime","hs.screening_by","hsl.screening_level as 
             hr_level","hss.screening_status as 
             hr_status","hr.candidate_name","hsm.screening_mode as 
          hr_mode","hire_screening.created_date","hs.screening_date"])
            ->innerJoin('hire_screening as hs','hs.resume_id = 
            hire_screening.resume_id')
            ->leftJoin('hire_screening_level as 
           hsl','hire_screening.screening_level = hsl.id')
            ->leftJoin('hire_screening_mode as 
           hsm','hire_screening.screening_mode = hsm.id')
            ->leftJoin('hire_screening_status as 
           hss','hire_screening.screening_status = hss.id')
            ->leftJoin('hire_resume as 
           hr','hire_screening.resume_id=hr.resume_id')
            //->where(['hire_screening.created_date = MaxDateTime'])
            ->groupBy(['resume_id']);
            //->having(['hire_screening.created_date' => 
          'hs.MaxDateTime']);
           $query->orderBy(['created_date' => SORT_DESC]);

但它没有显示出答案。 我需要与最新创建日期不同的resume_id。 sql查询显示正确的答案。我想在我的搜索模型中编写此查询。请帮我把这个问题转换成yii2。

1 个答案:

答案 0 :(得分:1)

如果有一个表MyTable,那么您可以使用resume_id对表格进行简单的查询分组:

SELECT 
  screening_id, 
  resume_id, 
  screening_by, 
  screening_date, 
  screening_level, 
  screening_mode, 
  screening_status, 
  reject_reason, 
  remarks, 
  created_by, 
  MAX(created_date) AS created_date
FROM MyTable
GROUP BY resume_id;

使用简化查询有助于避免错误。您还可以使用查询创建view或存储的procedure,并从您的PHP代码中调用它。