访问子查询内部联接中的父列

时间:2014-09-16 22:39:54

标签: mysql join subquery

SELECT p.id                      AS 'project_id', 
       p.hours                   AS 'budgeted_hours', 
       p.workedhours             AS 'worked_hours', 
       (SELECT Sum(tl.hours) AS total 
        FROM   tasks t 
               INNER JOIN tasklogs tl 
                       ON ( t.projects_id = 9000
                            AND tl.tasks_id = t.id ) 
        GROUP  BY t.projects_id) AS foo 
FROM   projects AS p 
WHERE  1 = 1 
       AND p.isactive = 1 
GROUP  BY p.id 

此查询正常,但项目ID是硬编码的(子查询中为9000)。我尝试将9000替换为projects.id或替换为p.id。这会导致语法错误:

SELECT p.id                      AS 'project_id', 
       p.hours                   AS 'budgeted_hours', 
       p.workedhours             AS 'worked_hours', 
       (SELECT Sum(tl.hours) AS total 
        FROM   tasks t 
               INNER JOIN tasklogs tl 
                       ON ( t.projects_id = p.id
                            AND tl.tasks_id = t.id ) 
        GROUP  BY t.projects_id) AS foo 
FROM   projects AS p 
WHERE  1 = 1 
       AND p.isactive = 1 
GROUP  BY p.id 

结果为[Err] 1054 - Unknown column 'p.id' in 'on clause'。还尝试添加ON

SELECT   p.id          AS 'project_id', 
         p.hours       AS 'budgeted_hours', 
         p.workedhours AS 'worked_hours', 
         ( 
                    SELECT     Sum(tl.hours) AS total 
                    FROM       tasks t 
                    INNER JOIN tasklogs tl 
                    ON         ( 
                                          t.projects_id= p.id 
                               AND        tl.tasks_id=t.id ) 
                    GROUP BY   t.projects_id ) AS foo 
on t.projects_id = p.id
FROM     projects AS p 
WHERE    1=1 
AND      p.isactive = 1 
GROUP BY p.id

这显然也是错误的。我只是不想知道如何访问p.id

2 个答案:

答案 0 :(得分:2)

我不是MySQL专家,但您是否尝试过这个子查询?

                SELECT     Sum(tl.hours) AS total 
                FROM       tasks t 
                INNER JOIN tasklogs tl 
                ON         tl.tasks_id = t.id
                WHERE      t.projects_id = p.id
                GROUP BY   t.projects_id

答案 1 :(得分:1)

试试这个:

SELECT p.id                      AS 'project_id', 
       p.hours                   AS 'budgeted_hours', 
       p.workedhours             AS 'worked_hours', 
       (SELECT Sum(tl.hours) AS total 
        FROM   tasks t 
               INNER JOIN tasklogs tl 
                       ON ( tl.tasks_id = t.id ) 
        GROUP  BY t.projects_id
        HAVING t.projects_id = p.id) AS foo 
FROM   projects AS p 
WHERE  1 = 1 
       AND p.isactive = 1 
GROUP  BY p.id