2016-08-12 3 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의 레코드가 더 높습니다.

나는 다음과 같은 쿼리를보십시오 :

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 

을하지만 결과는 다음과 같이이다 : 여기에 part_hours 및 part_amt 열이 어떻게 쿼리를 변경하는 아이디 (2)에서 페치

 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 

.

+0

실제 테이블을 포함하도록 편집을 수정하십시오 찾아주세요. –

+0

자세한 내용, 추가 답변. 어떤 테이블 값과 결과 –

+0

내 질문이 바뀝니다. 도와주세요 – Nisanth

답변

1

dateidMAX()을 추가 할 필요가 없습니다. 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

하지만 id2에서 part_hours와 part_amt의 값이 가장 큰 테이블 (hr_emp_job_compensation)이 무엇을하고 싶은지를 의미합니다. hr_emp_job_compensation 테이블 – Nisanth

+0

의 최대 날짜로 결과를 가져오고 싶습니다. 내 질문이 바뀝니다. 제발 도와주세요 – Nisanth

+0

우리는 '일하는'과 매우 다른 정의를 가지고 있습니다! – Strawberry