Reputation: 32180
I have a schema that looks like this
id, time, child_id
so its something like
1, 15, 2
2, 19, nil
3, 20, 5
4, 1, nil
5, 100, nil
I need to get the difference between the time of the parent and its child
so for the above data the result would be
id | time_difference
-------------------
1 | 4
3 | 80
so if a row has a child, it would take the child's time and subtract it from the parent. Assume that children don't have children of their own (a row is either a parent or a child)
Upvotes: 0
Views: 51
Reputation: 1842
This approach let you choose the time unit of difference, say you want your time difference in seconds, minutes, hours.
mysql has an issue with time differences that hasn`t been fixed since long time ago.:
Select
a.id, Time_To_Sec(b.time) - Time_To_Sec(a.time) As time_difference
From your_table a Left Outer Join
your_table b On a.id = b.child_id
Group By 1
Upvotes: 0
Reputation:
As you only have a single level of parent/child, this can be done with a self join:
select p.id,
c.time - p.time as time_difference
from the_table p
join the_table c on c.id = p.child_id
where p.child_id is not null;
SQLFiddle: http://sqlfiddle.com/#!2/e882e/1
Upvotes: 4