将LEFT JOIN子查询限制为1个结果

时间:2014-11-21 02:25:05

标签: mysql sql

下面的查询似乎是LIMIT all 结果为LEFT JOINed,因此子查询中的总数只有1.如何让它成为LIMIT以便我得到一个1:1行与projects中存储的最后一个日期之间的projects_hours_archive匹配,该日期存储了每周一次在cron作业上收集的projects.projected_hours记录?

projected_hours_archive包含以下列:idproject_idhoursdatetime

SELECT
    GROUP_CONCAT( projected_hours_last.date, '|', projected_hours_last.number ) AS 'projected_last_info'
FROM
projects


LEFT JOIN (
    SELECT *
    FROM
    projected_hours_archive
    ORDER BY date DESC
    LIMIT 1
) AS projected_hours_last ON ( projected_hours_last.project_id = projects.id )

WHERE projected_hours > 0

GROUP BY projects.id

我尝试使用MySQL Limit LEFT JOIN Subquery after joining,但没有成功。如果我删除子查询中的LIMIT,我会得到太多结果。

2 个答案:

答案 0 :(得分:4)

在子查询中使用group by并获得每个项目的最大日期。

编辑:根据OP评论,添加第二个最大日期。

使用此mysql how to get 2nd highest value with group by and in a left join的技巧。

SELECT
    GROUP_CONCAT( projected_hours_last.secondMaxDate, '|', projected_hours_last.number ) AS 'projected_last_info'
FROM
projects


LEFT JOIN (
    SELECT project_id, max(date) as maxDate,
           substring_index(substring_index(group_concat(date order by date desc), ',', 2), ',', -1
                            ) as secondMaxDate
    FROM
    projected_hours_archive
    group by project_id
) AS projected_hours_last ON ( projected_hours_last.project_id = projects.id )

WHERE projected_hours > 0

GROUP BY projects.id

答案 1 :(得分:1)

我有同样的问题。

我想您的字段projects.project_id是唯一的(因此该表中没有没有重复的内容)。否则,您可以像以前一样使用DISTINCT(projects.project_id)GROUP BY projects.project_id

解决方案1(在加入时使用GROUP BY):

        SELECT  a1.project_id,
                GROUP_CONCAT(a2.date, '|', a2.number ) AS 'projected_last_info'
        FROM projects a1
        LEFT JOIN (
            SELECT b1.project_id, b1.date, b1.number
            FROM projected_hours_archive b1 
            ORDER BY b1.date DESC
            GROUP BY b1.project_id
        ) a2 ON a2.project_id = a1.project_id
        WHERE a1.projected_hours > 0

解决方案2(直接在SELECT语句的子查询中使用LIMIT):

        SELECT  a1.project_id,
                (SELECT GROUP_CONCAT(a2.date, '|', a2.number )
                    FROM projected_hours_archive b1
                    WHERE b1.project_id = a1.project_id
                    ORDER BY b1.date DESC
                ) AS 'projected_last_info'
        FROM projects a1
        WHERE a1.projected_hours > 0