将2个mysql查询合并到一个具有唯一行的表中

时间:2012-10-03 03:40:48

标签: mysql inner-join

我正在尝试完成一个查询,显示每个项目的总小时数,格式如下:

Project Name |  Hours
Project A    |  2
Project B    |  6
Project C    |  8

我有两个SQL查询,用于计算每个项目的小时数。这是必要的,因为每个查询都有不同的JOIN:

例如,如果time_records.parent_type ='Task',那么Join就是:

INNER JOIN time_records
ON time_records.parent_id = project_objects.id

如果time_records.parent_type ='Project',则Join为:

INNER JOIN time_records
ON projects.id = time_records.parent_id

我正在尝试将这两个查询合并到一个表中,但是我遇到的问题是表重复项目,而不是将它们组合到每个项目的一个唯一行中(类似于数据透视表的工作方式)。

这是我当前的查询:

(SELECT projects.name AS expr1
     , sum(time_records.value) AS expr2
FROM
  project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
WHERE
  time_records.parent_type = 'Task' 
GROUP BY 
  projects.name)

UNION ALL

(SELECT projects.name AS expr1
      , sum(time_records.value) as expr2
FROM
   projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
WHERE
  time_records.parent_type = 'Project'
GROUP BY 
  projects.name)

以下是目前的输出方式:

Project Name | Hours
Project A | 2
Project B | 6
Project C | 8
Project A | 4

我需要项目A在一行上,显示6小时的值,而不是两行。我尝试了UNION操作,但这没有帮助。

2 个答案:

答案 0 :(得分:1)

你可以尝试一下,看看这是否有效?

SELECT X.expr1, SUM(X.expr2)
FROM 
  (SELECT 
    projects.name AS expr1
    , sum(time_records.value) AS expr2
  FROM project_objects
  INNER JOIN projects
    ON projects.id = project_objects.project_id
  INNER JOIN time_records
    ON time_records.parent_id = project_objects.id
  WHERE time_records.parent_type = 'Task' 
  GROUP BY projects.name

  UNION

  SELECT 
    projects.name AS expr1
    , sum(time_records.value) as expr2
  FROM projects
  INNER JOIN time_records
    ON projects.id = time_records.parent_id
  WHERE time_records.parent_type = 'Project'
  GROUP BY projects.name) X
GROUP BY X.expr1

答案 1 :(得分:0)

使用OR条件连接

修改

检查一下:最有可能这对你有用。 Sum results from two select statements

SELECT projects.name AS nameval
     , sum(time_records.value) AS total
FROM ((SELECT projects.name AS expr1
     , sum(time_records.value) AS expr2
FROM
  project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
WHERE
  time_records.parent_type = 'Task' 
GROUP BY 
  projects.name)

UNION ALL

(SELECT projects.name AS expr1
      , sum(time_records.value) as expr2
FROM
   projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
WHERE
  time_records.parent_type = 'Project'
GROUP BY 
  projects.name)) t group by expr1