2017-05-24 73 views
0

我有一个查询:如何在yii2查询中使用MAX函数?

​​

这是我的表:

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

如果有表MyTable,那么你可以通过使用resume_id查询simplier分组表:

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代码中调用此函数。