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
?
答案 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