0

我无法让查询从两个表中提取数据,中间有第三个表。让我告诉你我的意思。

*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 working 每个项目每天可以有多个提交。例如,几行可能看起来像

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

任何帮助将不胜感激!

4

2 回答 2

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
于 2012-11-21T11:32:09.663 回答
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
于 2012-11-21T11:40:18.683 回答