所以我正在尝试计算零件数量,任务数量,每个工作的数量以及制造每项工作所花费的时间,但我得到了一些时髦的结果。如果我运行这个:
SELECT
j.id,
mf.special_instructions,
count(distinct p.id) as number_of_different_parts,
count(distinct t.id) as number_of_tasks,
SUM(distinct j.quantity) as number_of_assemblies,
SUM(l.time_elapsed) as time_elapsed
FROM
sugarcrm2.mf_job mf
INNER JOIN ramses.jobs j on
mf.id = j.mf_job_id
INNER JOIN ramses.parts p on
j.id = p.job_id
INNER JOIN ramses.tasks t on
p.id = t.part_id
INNER JOIN ramses.batch_log l on
t.batch_id = l.batch_id
WHERE
mf.job_description LIKE "%BACKBLAZE%" OR
mf.customer_name LIKE "%BACKBLAZE%" OR
mf.customer_ref LIKE "%BACKBLAZE%" OR
mf.technical_company_name LIKE "%BACKBLAZE%" OR
mf.description LIKE "%BACKBLAZE%" OR
mf.name LIKE "%BACKBLAZE%" OR
mf.enclosure_style LIKE "%BACKBLAZE%" OR
mf.special_instructions LIKE "%BACKBLAZE%"
Group by j.id
我现在可以获得准确的零件和任务编号,但time_elapsed总和不正确。问题是什么?
当我使用distinct
进行尝试时,我得到的数字很低(当我正在寻找接近10,000的东西时,就像1到30之间的东西一样。)
更新:这是创建代码:
关系是这样的:
我试图从每个mf_job的batch_log中获取所有time_loglap,其中一个字段中包含backblaze一词以及部件,任务和程序集的数量。这一切都需要按job.id或mf_job.id
分组答案 0 :(得分:3)
尝试将查询重写为:
SELECT
j.id,
mf.special_instructions,
count(p.id) as number_of_different_parts,
count(t.id) as number_of_tasks,
SUM(j.quantity) as number_of_assemblies,
SEC_TO_TIME(SUM(l.seconds_elapsed)) as time_elapsed
FROM
sugarcrm2.mf_job mf
INNER JOIN ramses.jobs j on
mf.id = j.mf_job_id
INNER JOIN ramses.parts p on
j.id = p.job_id
INNER JOIN ramses.tasks t on
p.id = t.part_id
INNER JOIN (
SELECT rl.batch_id
, SUM(TIME_TO_SEC(rl.time_elapsed)) as seconds_elapsed
FROM ramses.batch_log rl
GROUP BY rl.batch_id
) l ON (t.batch_id = l.batch_id)
WHERE
mf.job_description LIKE "%BACKBLAZE%" OR
mf.customer_name LIKE "%BACKBLAZE%" OR
mf.customer_ref LIKE "%BACKBLAZE%" OR
mf.technical_company_name LIKE "%BACKBLAZE%" OR
mf.description LIKE "%BACKBLAZE%" OR
mf.name LIKE "%BACKBLAZE%" OR
mf.enclosure_style LIKE "%BACKBLAZE%" OR
mf.special_instructions LIKE "%BACKBLAZE%"
GROUP BY j.id WITH ROLLUP
答案 1 :(得分:2)
您需要将查询更改为:
SELECT
...
SEC_TO_TIME(SUM(TIME_TO_SEC(l.time_elapsed))) as time_elapsed
此外,LIKE '%...'
行将使查询速度变慢,因为无法使用此参数。
如果您能够使用MyISAM,则可以在这些列上使用全文索引并使用以下代码:
WHERE MATCH(mf.job_description,mf.customer_name,mf.customer_name,...)
AGAINST ('BACKBLAZE' IN NATURAL LANGUAGE MODE)
请参阅:
http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
http://www.petefreitag.com/item/477.cfm
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_time-to-sec
答案 2 :(得分:-1)
听起来问题是多个任务可以在同一批次中,和/或多个部分可以在同一个任务中。例如,假设您的工作有3个部分,每个部分都有一个任务,并且所有3个任务都在同一批次中。您将为该批次添加三次时间。但是不同的也不会起作用,因为如果你有5个不同的批次都需要300秒,它们将不会被认为是不同的。
在这种情况下,子查询通常是要走的路。您可以加入一个选择不同的batch_log
(或j.id
),p.job_id
和l.batch_id
的子查询,而不是直接加入l.time_elapsed
(第一个是对于加入,第二个只是为了正确计算distinct,而第三个用于实际值)。然后你可以从那里加总l.time_elapsed
。这样每个批次只计算一次。
答案 3 :(得分:-1)
批次(l)表没有名为time_elapsed的字段 任务确实如此
SUM(t.time_elapsed) as time_elapsed
- 或 -
SUM(l.actual_time) as time_elapsed