mysql将1张表加入另外2张表

时间:2019-02-22 20:41:10

标签: mysql

我需要将项目中每个任务的实际工时与估计工时进行比较。信息位于3个不同的表中

任务表:包含所有项目任务信息

  • 任务ID(键)
  • 任务名称
  • 项目名称

时间表表:包含记录到任务的实际小时数

  • 任务ID
  • 任务名称
  • 小时(总和)[每个任务的多个时间表记录]

任务所有者表:包含分配给任务的估计工时

  • 任务ID
  • 任务名称
  • 估计小时数(总和)[每个任务的多个任务所有者记录]

我需要从“任务”表中获取任务信息,从时间表表中获取实际工时总数,并从“任务所有者”表中获取预计工时总数

这是它的外观:

Project Name | Task Name | Actual Hours | Estimated Hours

这是我的开始查询,向我显示每个项目任务的实际总时数。现在,我需要知道如何为估算的总时数添加一列

SELECT
tasks."Project Name" AS "Project Name",
tasks."Task Name" AS "Task Name",
sum("Timesheets"."Hours") AS "Hours"
FROM "Tasks" join "Timesheets" ON "Tasks"."Task ID" = "Timesheets"."Task ID"
GROUP BY tasks."Project Name", tasks."Task Name"

4 个答案:

答案 0 :(得分:2)

可以将聚合列分配给select子查询:

SELECT
tasks."Project Name" AS "Project Name",
tasks."Task Name" AS "Task Name",
(select sum("Timesheets"."Hours" FROM "Timesheets" where "Timesheets"."Task ID" = "Tasks"."Task ID") as "Hours",
(select sum("Task Owner"."Hours" FROM "Timesheets" where "Task Owner"."Task ID" = "Tasks"."Task ID") as "Estimated Hours"
FROM "Tasks"

答案 1 :(得分:1)

您应该添加另一个联接:

SELECT
    tasks.`Project Name` AS `Project Name`,
    tasks.`Task Name` AS `Task Name`,
    sum(`Timesheets`.`Hours`) AS `Hours`
    sum(`Task Owner`.Estimated Hour`) AS `Estimated Hour`
    FROM `Tasks` 
    join `Timesheets` ON `Tasks`.`Task ID` = `Timesheets`.`Task ID`
    join `Task Owner`  ON `Tasks`.`Task ID` = `Task Owner`.`Task ID`

GROUP BY tasks.`Project Name`, tasks.`Task Name`

我想建议您使用反斜线代替表名和列名的双引号。

答案 2 :(得分:1)

这可能有助于在此处预先汇总您在子查询中的实际时间和估计时间,然后将其加入。如果您的 {% for book in books %} <li> {{ book.title }} # here </li> {% endfor %} dependencies { classpath 'com.android.tools.build:gradle:3.3.1' classpath 'com.google.gms:google-services:4.2.0' 表中有很多行,这尤其重要每个不同的Task Owner

Timesheets

使用此方法可确保每个子查询返回每个task id的唯一记录,并包含估计或实际小时数之和。

答案 3 :(得分:1)

您不能仅将三个表直接连接在一起,因为“时间表”和“任务所有者”在“任务ID”列中都可以有重复的值。为了避免在连接时产生更多的行,您需要预先对这些表进行分组。可以使用子查询来完成,但是使用WITH可以得到干净的代码。

WITH actual AS (
    SELECT
        "Task ID",
        SUM(Hours) AS hours
    FROM "Task Owner"
    GROUP BY "Task ID"
),

estimated AS (
    SELECT
        "Task ID",
        SUM(Hours) AS hours
    FROM Timesheets
    GROUP BY "Task ID"
)

SELECT 
    t."project name"      AS "Project Name", 
    t."task name"         AS "Task Name", 
    a.hours               AS "Actual Hours"
    e.hours               AS "Estimated Hours"
FROM tasks t
LEFT JOIN actual a
    ON t."task id" = a."task id" 
LEFT JOIN estimated e
    ON t."task id" = e."task id" 
GROUP  BY tasks."project name", 
    tasks."task name"