如何使用左连接获取所有行获取第二个表中的最新行

时间:2013-03-06 14:08:59

标签: mysql join

我正在尝试按照in this answer说明如何获取连接表中的最新行。

我有两张桌子。

Projects : id, title
Status : project_id, status_id, created(DATETIME)

当我知道项目ID(例如= 2)时,我有正确的查询来选择最新的状态更新。

SELECT projects. * , project_state_project_map.status_id AS status, 
project_state_project_map.created AS status_created
FROM projects
LEFT JOIN (

    SELECT * 
    FROM project_state_project_map
    WHERE project_id = 2
    ORDER BY created DESC 
    LIMIT 1
    )
project_state_project_map ON project_state_project_map.project_id = projects.id
WHERE projects.id = 2
LIMIT 1

但是,我无法弄清楚如何选择具有当前状态的所有项目。我需要更改为sql以获取具有最新状态的所有项目。

1 个答案:

答案 0 :(得分:1)

我建议更改您的查询以使用聚合函数来获取状态的最新日期:

SELECT p. *, 
  pm1.status_id AS status, 
  pm1.created AS status_created
FROM projects p
LEFT JOIN project_state_project_map pm1
  ON pm1.project_id = p.id
INNER JOIN 
(
  SELECT max(created) MaxDate, project_id
  FROM project_state_project_map
  WHERE project_id = 2
  GROUP BY project_id
) pm2 
  ON pm1.project_id = pm2.project_id
  AND pm1.created = pm2.MaxDate
WHERE p.id = 2

这将获得每个项目的max(created)日期,然后此结果用于返回该日期的状态。

这也可以写成:

SELECT p. *, 
  pm.status_id AS status, 
  pm.created AS status_created
FROM projects p
LEFT JOIN
(
  SELECT pm1.project_id,
    pm1.status_id,
    pm1.created
  FROM project_state_project_map pm1
  INNER JOIN 
  (
    SELECT max(created) MaxDate, project_id
    FROM project_state_project_map
    WHERE project_id = 2
    GROUP BY project_id
  ) pm2
    ON pm1.project_id = pm2.project_id
    AND pm1.created = pm2.MaxDate
) pm
  ON pm.project_id = p.id
WHERE p.id = 2;