Search code examples
mysqljoinsumduplication

If the where condition is on a joined table, will I get duplicated results?


I have three tables, one is tasks which are tasks that factory workers complete by putting them into batches, which is another table, each task has a batch_id, multiple tasks can have the same batch_id. The third table is the batch_log where all time that someone has worked on a batch is recorded in the form of a unique id, a batch_id, the person's userid, the start_time and the end_time.

Each task has an estimated_recurring time in seconds and an estimated_nonrecurring time in seconds. I'm looking to get the sum of both of those fields grouped by the operation_id which is a field in the tasks table to represent whether it is a laser cutting, deburr, painting, etc task.

The issue is that I only want the tasks that have batches that were in the batch_log during a time_period. Batches have multiple entries in the batch_log table.

Here is what I'm trying:

SELECT 
  operation_id, SUM(t.estimated_nonrecurring + t.estimated_recurring) / 3600 as work_completed
FROM tasks t
INNER JOIN batch_log l on t.batch_id = l.batch_id
WHERE 
  l.start_time BETWEEN DATE("10:00:00") AND DATE(NOW())
AND
  l.time_elapsed < "10:00:00"
GROUP BY t.operation_id

I'm concerned that I will get a higher estimate than is real because multiple entries in the task table can have the same batch.


Solution

  • Because you only want the times based on tasks that were in your batch log file what you posted will definately not work.

    Assuming you have 3 tables: Tasks, Batches, and BatchLog.

    You'll want this:

    SELECT
          SUM(t.estimated_nonrecurring + t.estimated_recurring) / 3600 as work_completed,
          t.OperationID
    FROM
          Tasks t
    INNER JOIN
           Batches b
    ON
           b.BatchID = t.BatchID
    INNER JOIN
           BatchLog bl
    ON
           bl.BatchID = b.BatchID
    WHERE  
      bl.start_time BETWEEN DATE("2011-08-01") AND DATE(NOW())
    GROUP BY
           t.OperationID