Search code examples
mysqljoininner-joinouter-join

Calculate difference in dates using JOIN in MySql


I have MySQL table which has logId as the foreign key

enter image description here

The other table has logId as one column and corresponding startDate and endDate

enter image description here

I want to write a JOIN in a way such that my output provides difference between startDate and endDate (in hours) for every server.

enter image description here

I have written the following JOIN but need help to calculate to the difference in dates and show it as TotalTime

select server, totaltime from table1
inner join table2 on table1.logId = table2.logId

Solution

  • SELECT 
        t1.server, 
        TIMESTAMPDIFF(HOUR,t2.StartDate, t2.EndDate) AS TotalTime
    FROM 
        table1 t1
        LEFT JOIN table2 t2 ON t1.logId = t2.logId