2016-08-12 64 views
1

最近的日期我有一個像下面3個表選擇記錄:如何根據在MySQL

hr_emp_job_compensation:

id date   fkEmp_id basic_wage part_hours part_amt 

    1 04-01-2016 1   4500  35   120 
    2 04-01-2016 3   3800  30   150 
    3 08-01-2016 3   3200  30   100 

hr_emp_job_info:

id fkEmp_id 

    1  1 
    2  3 

hr_emp_info:

id employee_id first_name 

    1  001  Ram 
    2  002  Lak 
    3  003  jai 
    4  004  shiva 

我想選擇來自表1的記錄基於Date值較高的列。

我嘗試以下查詢:

SELECT t1.fkEmp_id,max(t1.date),max(t1.id) as uid,t1.part_hours,t1.part_amt, t3.first_name, t3.employee_id 
FROM `hr_emp_job_compensation` as t1 
inner join `hr_emp_job_info` as t2 on t1.fkEmp_id = t2.fkEmp_id 
left join `hr_emp_info` as t3 on t3.id = t1.fkEmp_id 
group by t1.fkEmp_id 

但結果是看起來象下面這樣:

 fkEmp_id max(t1.date) uid part_hours part_amt first_name employee_id 
     1   2016-01-04  1  35   120  Ram   001 

     3   2016-01-08  3  30   150  Jai   003 

這裏part_hours和part_amt列是從ID 2.如何更改查詢取。

+0

請解決您的編輯,包括實際的表。 –

+0

更多細節,更多答案。什麼表值和什麼結果 –

+0

我改變我的問題。請幫助我 – Nisanth

回答

1

無需爲dateid添加MAX()。您可以在WHERE條款中處理MAX(date)

SELECT t1.fkEmp_id, t1.date as `date`, t1.id as uid, 
     t1.part_hours, t1.part_amt, 
     t3.first_name, t3.employee_id 
FROM `hr_emp_job_compensation` as t1 
INNER JOIN `hr_emp_job_info` as t2 on t2.fkEmp_id = t1.fkEmp_id 
LEFT JOIN `hr_emp_info` as t3 on t3.id = t1.fkEmp_id 
WHERE t1.`date`= (SELECT MAX(`date`) 
        FROM `hr_emp_job_compensation` 
        WHERE fkEmp_id = t1.fkEmp_id); 

請找到Working Demo

+0

但是,如果我的表(hr_emp_job_compensation)在id 2中具有part_hours和part_amt的最高值意味着我想要做的事情。我想通過hr_emp_job_compensation表的最大日期得到結果 – Nisanth

+0

我改變了我的問題。請幫助我 – Nisanth

+0

我們對「工作」的定義非常不同。 – Strawberry