views:

47

answers:

1

I want get the time used for a case so I can create an overview.

The SELECT query for the cases looks like this:

SELECT bc.id, bc.title, bc.estimateCurrent FROM cases bc

For one case I can get the used time like this:

SELECT SUM(TIME_TO_SEC(TIMEDIFF(dateEnding, dateBeginning))) AS calculatedTime FROM timesheet WHERE `#case` = ?

How do I connect both so I have one value for the overview SELECT query? Basically I would want the table to look like this:

id|title|estimateCurrent|timeusedinsec
 1|case1|             20|    2000
 2|case2|             40|    2500
 3|case3|             70|       0

Is that possible? I didn't want to have a for each query on the php side which would result in several queries. Would a view help?

+1  A: 

Assuming the timesheet column #case refers to bc.id, you could use a join like this:

SELECT 
    bc.id, bc.title, bc.estimateCurrent,
    SUM(TIME_TO_SEC(TIMEDIFF(dateEnding, dateBeginning)))
FROM cases bc
JOIN timesheet ts on ts.`#case` = bc.id
GROUP BY bc.id, bc.title, bc.estimateCurrent

The GROUP BY defines how SUM() works. Here, it will make SUM() add up all rows with the same #case number.

Andomar
awesome I was trying to figure this out really badly :D
Thomaschaaf
You may want to consider the join type here as cases that no-one has yet worked on will not be visible with a natural join.
Steve Weet
LEFT JOIN it is :)
Thomaschaaf
Is the GROUP BY with the different things really important? Would GROUP BY bc.id be enough?
Thomaschaaf
Yes the GROUP BY clause must name all columns that are not aggregates or constants
Steve Weet
LEFT JOIN is same as JOIN, LEFT is the default. It's a best practice to specify every non-aggregated column in the GROUP BY clause. But MySQL is one of the few databases that does not enforce this, so GROUP BY bc.id would be enough.
Andomar
INNER JOIN is the default is most DBs
araqnid