如何从这样的三个表中查询

时间:2018-08-19 16:16:13

标签: mysql

假设我有三个表项目,客户端和工作。像这样

项目表

---------------------------------------------------------
|   project_id  |   project_name    |   client_id       |
---------------------------------------------------------
|       1       |       abc         |       1           |
|       2       |       xyz         |       2           |
---------------------------------------------------------

客户表

-------------------------------------
|   client_id   |   client_name     |
-------------------------------------
|       1       |       a           |
|       2       |       b           |
-------------------------------------

工作表

---------------------------------------------------------
|   work_id     |       work_cost   |   project_id      |
---------------------------------------------------------
|       1       |       100         |       1           |
|       2       |       200         |       1           |
|       3       |       100         |       2           |
|       4       |       100         |       1           |
|       5       |       100         |       1           |
|       6       |       200         |       2           |
---------------------------------------------------------

在这里我要从三个表中查询并显示结果。

------------------------------------------------------------------------
|   project_id  |   project_name    |   client_name |   total_work_cost |
------------------------------------------------------------------------
|       1       |       abc         |       a       |       500         |
|       2       |       xyz         |       b       |       300         |
------------------------------------------------------------------------

这里total_work_cost表示,假设项目1在工作表中有4条记录。我想对项目1的工作表中的所有work_cost求和。

我已经尝试过这样-

SELECT project.*, c.client_name, SUM(w.work_cost) as total_work_cost
    FROM project
    LEFT JOIN client as c ON project.client_id = c.client_id
    INNER JOIN work as w on project.project_id = w.project_id
    ORDER BY projects.project_id

1 个答案:

答案 0 :(得分:1)

您缺少聚合逻辑,即查询中的GROUP BY子句:

SELECT p.project_id, p.project_name, c.client_name, SUM(w.work_cost) as total_work_cost
FROM project as p LEFT JOIN client as c 
ON p.client_id = c.client_id
LEFT JOIN work as w 
on p.project_id = w.project_id
GROUP BY p.project_id, p.project_name, c.client_name
ORDER BY p.project_id