使用 MAX 随机播放记录

Using MAX shuffles records around

我有以下影响table:

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

我有以下查询,但它混淆了行数据,因为 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

你可以看到对那个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`
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