How to combine two rows and calculate the time difference between two timestamp values in MySQL?

前端 未结 6 1013
误落风尘
误落风尘 2020-12-06 06:14

I have a situation that I\'m sure is quite common and it\'s really bothering me that I can\'t figure out how to do it or what to search for to find a relevant example/soluti

6条回答
  •  攒了一身酷
    2020-12-06 06:52

    I believe this could be a simpler way to reach your goal:

    SELECT
        start_log.name,
        MAX(start_log.ts) AS start_time,
        end_log.ts AS end_time,
        TIMEDIFF(MAX(start_log.ts), end_log.ts)
    FROM
        log AS start_log
    INNER JOIN
        log AS end_log ON (
                start_log.name = end_log.name
            AND
                end_log.ts > start_log.ts)
    WHERE start_log.eventtype = 'start'
    AND end_log.eventtype = 'stop'
    GROUP BY start_log.name
    

    It should run considerably faster as it eliminates one subquery.

提交回复
热议问题