使用MAX shuffles记录周围

时间:2015-01-19 17:50:28

标签: mysql max

我有以下影响表:

enter image description here

我需要为利益相关者获得最新的影响......

我有以下查询,但它混合了行数据,因为MAX没有返回完整记录:

SELECT stakeholder_id, MAX(created_at) AS maxca, influence
FROM influences
WHERE
project_id = 1 AND
deleted_at IS NULL
GROUP BY stakeholder_id

enter image description here

您可以看到对该maxca和stakeholder_id的影响应为3,而不是5。

我如何克服这个问题? 我现在的完整陈述是这样的:

SELECT `stakeholders`.*, `influences`.`influence`
FROM `project_stakeholder`
INNER JOIN `stakeholders` ON `project_stakeholder`.`stakeholder_id` = `stakeholders`.`id`
INNER JOIN `stakeholder_profiles` ON `stakeholder_profiles`.`stakeholder_id` = `stakeholders`.`id`
LEFT JOIN `stakeholder_profile_tag` ON `stakeholder_profile_tag`.`stakeholder_profile_id` = `stakeholder_profiles`.`id`
LEFT JOIN `stakeholder_profile_group` ON `stakeholder_profile_group`.`stakeholder_profile_id` = `stakeholder_profiles`.`id`
LEFT JOIN `influences` ON `influences`.`stakeholder_id` = `stakeholders`.`id`
INNER JOIN `projects` ON `project_stakeholder`.`project_id` = `projects`.`id`


LEFT JOIN (

    /*! This is the bit that doesn't work */
    SELECT stakeholder_id, MAX(created_at) AS maxca
    FROM influences
    WHERE
    project_id = 1 AND
    deleted_at IS NULL
    GROUP BY stakeholder_id


) 

iu ON `iu`.`stakeholder_id` = influences.stakeholder_id AND 
iu.maxca = influences.created_at



WHERE `projects`.`id` = '1'
GROUP BY `stakeholders`.`id`

这似乎有效:

SELECT `stakeholders`.*, iu.influence
FROM `project_stakeholder`
INNER JOIN `stakeholders` ON `project_stakeholder`.`stakeholder_id` = `stakeholders`.`id`
INNER JOIN `stakeholder_profiles` ON `stakeholder_profiles`.`stakeholder_id` = `stakeholders`.`id`
LEFT JOIN `stakeholder_profile_tag` ON `stakeholder_profile_tag`.`stakeholder_profile_id` = `stakeholder_profiles`.`id`
LEFT JOIN `stakeholder_profile_group` ON `stakeholder_profile_group`.`stakeholder_profile_id` = `stakeholder_profiles`.`id`
INNER JOIN `projects` ON `project_stakeholder`.`project_id` = `projects`.`id`


LEFT JOIN (

    select i1.*
    from influences i1
    join
    (
        SELECT stakeholder_id, MAX(created_at) AS maxca
        FROM influences
        WHERE project_id = 1 
        AND deleted_at IS NULL
        GROUP BY stakeholder_id
    ) i2 on i1.stakeholder_id = i2.stakeholder_id
        and i1.created_at = i2.maxca

) iu ON `iu`.`stakeholder_id` = stakeholders.id



WHERE `projects`.`id` = '1'
GROUP BY `stakeholders`.`id`

1 个答案:

答案 0 :(得分:1)

select i1.*
from influences i1
join
(
    SELECT stakeholder_id, MAX(created_at) AS maxca
    FROM influences
    WHERE project_id = 1 
    AND deleted_at IS NULL
    GROUP BY stakeholder_id
) i2 on i1.stakeholder_id = i2.stakeholder_id
    and i1.created_at = i2.maxca