获取2个联合表的最大日期结果

时间:2017-01-01 03:33:56

标签: mysql sql

如何获取联合表的最大日期值?每当我使用GROUP BY时,我只获得第一个表的最大日期值。到目前为止,这是我的代码:

SELECT * FROM ((SELECT tc.id, tc.personnel_id, tpi.emp_status, tpi.firstname, tpi.lastname, tc.date_from, tc.date_to FROM tbl_contracts AS tc 
JOIN (SELECT personnel_id, MAX(date_to) AS Maxdatetime
FROM tbl_contracts
GROUP BY personnel_id) AS r 
ON tc.personnel_id = r.personnel_id AND tc.date_to = r.Maxdatetime 
LEFT JOIN tbl_personnel_info AS tpi 
ON tpi.id = tc.personnel_id 
WHERE tpi.firstname LIKE CONCAT('%', '', '%') 
AND tpi.lastname LIKE CONCAT('%', '', '%')
ORDER BY tc.date_to DESC)
UNION ALL 
(SELECT tpss.id, tpss.personnel_id, tpi.emp_status, tpi.firstname, tpi.lastname, tpss.date_from, tpss.date_to 
FROM tbl_personnel_sea_service AS tpss
JOIN (
SELECT personnel_id, MAX(date_to) AS Maxdatetime
FROM tbl_personnel_sea_service
GROUP BY personnel_id
 ) AS r 
ON tpss.personnel_id = r.personnel_id AND tpss.date_to = r.Maxdatetime
LEFT JOIN tbl_personnel_info AS tpi
ON tpi.id = tpss.personnel_id
WHERE tpi.firstname LIKE CONCAT('%', '', '%')
AND tpi.lastname LIKE CONCAT('%', '', '%')
AND agency_name = 'UMMI'
ORDER BY tpss.date_to DESC)) AS tmain
GROUP BY tmain.personnel_id

结果是正确的。但是,如果我使用GROUP BY tmain.personnel_id,则排序结果是错误的。它没有得到第二个表的最大日期值

Here's the screenshot of result

1 个答案:

答案 0 :(得分:1)

我建议你在整个专栏上收集小组并汇总日期,最后按date_to(或你需要的任何一列)订购 -

SELECT personnel_id,
  emp_status,
  first_name,
  lastname,
  MIN(date_from) date_from,
  MAX(date_to) date_to
FROM (
  (SELECT tc.id,
    tc.personnel_id,
    tpi.emp_status,
    tpi.firstname,
    tpi.lastname,
    tc.date_from,
    tc.date_to
  FROM tbl_contracts AS tc
  JOIN
    (SELECT personnel_id,
      MAX(date_to) AS Maxdatetime
    FROM tbl_contracts
    GROUP BY personnel_id
    ) AS r
  ON tc.personnel_id = r.personnel_id
  AND tc.date_to     = r.Maxdatetime
  LEFT JOIN tbl_personnel_info AS tpi
  ON tpi.id = tc.personnel_id
  WHERE tpi.firstname LIKE CONCAT('%', '', '%')
  AND tpi.lastname LIKE CONCAT('%', '', '%')
  ORDER BY tc.date_to DESC
  )
UNION ALL
  (SELECT tpss.id,
    tpss.personnel_id,
    tpi.emp_status,
    tpi.firstname,
    tpi.lastname,
    tpss.date_from,
    tpss.date_to
  FROM tbl_personnel_sea_service AS tpss
  JOIN
    (SELECT personnel_id,
      MAX(date_to) AS Maxdatetime
    FROM tbl_personnel_sea_service
    GROUP BY personnel_id
    ) AS r
  ON tpss.personnel_id = r.personnel_id
  AND tpss.date_to     = r.Maxdatetime
  LEFT JOIN tbl_personnel_info AS tpi
  ON tpi.id = tpss.personnel_id
  WHERE tpi.firstname LIKE CONCAT('%', '', '%')
  AND tpi.lastname LIKE CONCAT('%', '', '%')
  AND agency_name = 'UMMI'
  ORDER BY tpss.date_to DESC
  )) AS tmain
GROUP BY personnel_id,
  emp_status,
  first_name,
  lastname
ORDER BY date_to