用sum()子查询连接三个表

时间:2012-11-21 11:02:41

标签: mysql database join relational-database

我无法使用查询来处理从两个表中提取数据的情况,其中第三个表位于中间。让我告诉你我的意思。

*Table companies*
id int PK
name text 

*Table projects*
id int PK
company_id int FK
project_name text

*Table hours_worked*
id int pk
user_id int FK
project_id int FK
hours float
date_worked datetime

*Table users*
id int PK
user_name text

基本上,我需要的是一个查询,可根据用户ID 提取每家公司的总工作时数。

请注意,table_hours工作每个项目每天可以提交多个提交。例如,几行可能看起来像

id  project_id user_id  hours  date_worked
 1       1        1       2     20-08-2012
 2       1        1       1.5   20-08-2012
 3       2        1       3     21-08-2012
 4       2        2       12    22-08-2012

我想要的结果将是一个返回如下内容的查询:

company_name     total_hours
 Bobs Kitchens       25
 Mikes Bikes         67

返回每个公司(非项目)的总工作小时数,例如,用户ID为1的用户。

以下是我尝试过无效的查询:

        SELECT DISTINCT companies.name as company_name,
        companies.id as company_id,
        (
          SELECT SUM(hours_worked.hours) FROM hours_worked
          WHERE projects.id = hours_worked.project_id
          AND projects.company_id = company_id
        ) as total_hours
        FROM hoursworked, companies, projects
        WHERE projects.company_id = company_id
        AND projects.company_id = projects.company_id
        AND hours_worked.user_id = 1
        GROUP BY companies.id

这给了我一个奇怪的结果,其中每个total_hours字段显示一个非常奇怪的数字。 75不是任何公司的正确总小时数!

company_name   total_hours
Mikes Kitchen      75
Charlies Bikes     75
 .....             75

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT c.name company_name, u.user_name, SUM(h.hours) total_hours
FROM projects p 
INNER JOIN companies c ON p.company_id = c.id 
INNER JOIN hours_worked h ON p.id = h.project_id 
INNER JOIN users u ON h.user_id = u.id
GROUP BY c.id, u.id

答案 1 :(得分:0)

我真是个傻瓜......实际上比我想象的容易得多。为了过度思考而欢呼。

我使用的查询是:

SELECT SUM(hours_worked.hours) as 'total_hours',
                companies.name
                FROM companies, hours_worked, projects
                WHERE companies.id = projects.company_id
                      AND hours_worked.project_id = projects.id
                      AND hours_worked.uid = 1
                      GROUP BY companies.id ORDER BY companies.name DESC