MySQL查询的总和

时间:2011-07-19 11:28:02

标签: mysql

我有一个很长的查询,导致我遇到一些问题。对于第一个子查询,我不断收到错误:“MySQL服务器版本用于在第5行'SELECT project.project_total_num_hours_quoted FROM project inner join time_recor'附近使用正确的语法。”

有问题的子查询是:

sum(SELECT
    project.project_total_num_hours_quoted
    FROM
    project inner join time_recording using(project_id)
    WHERE
    project.company_id = company.company_id
    AND project_is_retainer != 1
    AND time_recording.time_recording_event_start_datetime >= '2011-01-01' AND time_recording.time_recording_event_stop_datetime <= '2011-03-01'
    group by project_id
    ) AS hours_quoted,

返回一组结果。在较大的查询中,我只想得到总和。

SELECT 
SUM((unix_timestamp(time_recording.time_recording_event_stop_datetime)-unix_timestamp(time_recording.time_recording_event_start_datetime))/3600) AS total_time, 
company.company_label,

sum(SELECT
project.project_total_num_hours_quoted
FROM
project inner join time_recording using(project_id)
WHERE
project.company_id = company.company_id
AND project_is_retainer != 1
AND time_recording.time_recording_event_start_datetime >= '2011-01-01' AND time_recording.time_recording_event_stop_datetime <= '2011-03-01'
group by project_id
) AS hours_quoted,

(SELECT SUM(project.project_total_num_hours_quoted)
FROM project 
INNER JOIN time_recording ON project.project_id = time_recording.project_id
WHERE time_recording.time_recording_event_start_datetime>='2011-01-01'
AND project_is_retainer!=1
AND time_recording.time_recording_event_stop_datetime<='2011-03-01'
AND project.company_id!=1
) AS total_hours_quoted,

(
SELECT 
SUM((unix_timestamp(time_recording.time_recording_event_stop_datetime)-unix_timestamp(time_recording.time_recording_event_start_datetime))/3600) 
FROM time_recording 
INNER JOIN project ON time_recording.project_id = project.project_id 
WHERE project.company_id!=1 
AND project_is_retainer!=1
AND time_recording.time_recording_event_start_datetime>='2011-01-01'
AND time_recording.time_recording_event_stop_datetime<='2011-03-01'
)
AS total_hours

FROM time_recording 
INNER JOIN project ON time_recording.project_id = project.project_id
INNER JOIN company ON project.company_id = company.company_id
WHERE company.company_id!=1
AND project_is_retainer!=1
AND time_recording.time_recording_event_start_datetime>='2011-01-01'
AND time_recording.time_recording_event_stop_datetime<='2011-03-01'
GROUP BY company.company_id 
ORDER BY total_time desc 
LIMIT 7

2 个答案:

答案 0 :(得分:1)

在第一个子查询中,如果在外部查询中对其求和,则不需要该组。你错过了ON条款。

SELECT project.project_total_num_hours_quoted
FROM project inner join time_recording 
ON project.id=time_recording.project_id
WHERE
project.company_id = company.company_id
AND project_is_retainer != 1
AND time_recording.time_recording_event_start_datetime >= '2011-01-01' 
AND time_recording.time_recording_event_stop_datetime <= '2011-03-01'

答案 1 :(得分:1)

我强烈建议废弃这个并重新开始。

几个(如果不是全部)子选择可以合并为单个SELECT语句。外部SELECT是一个聚合操作,它选择未包含在GROUP BY子句中的非聚合值。 MySQL不优化推送谓词。而且你在查询中有冗余连接。