I'm struggling with a Mysql Code, and I have no clue how to solve this. I have two columns with time value on which I've ordered by desc in Mysql Query result.
I need to find out the differences between the 2nd row StateEndTime and the 1st-row StateStarTtime nd so on and display this in a new row/column. The final table should look like this :
ID Type StateStarTtime StateEndTime Min Difference
xxx YYY 03:57 03:59 00:02
xxx ZZZ 03:53 03:55 00:04
xxx ZZZ 03:46 03:49
Assuming ID is an auto increment column, this can be achieved in MySQL by self join technique:
SELECT
t1.ID,
t1.Type,
t1.StateStartTime,
t1.StateEndTime
(t1.StateStartTime - t2.StateEndTime) AS Min_Diff
FROM
Table1 t1
INNER JOIN
Table1 t2 ON t2.id = t1.id + 1
Is this what you trying to do?
mysql_query("SELECT *, `StateEndTime`-`StateStarTtime` AS `Min Difference`
FROM `TableName`");
This could be simplified in a MYSQL 8 with CTE and or the ROW_NUM function but this will work to get the solution you are after in most versions.
I've also casted your times as in the example they arent in the correct format, this may not be the case in your actual data.
SET @row_number_a = 0;
SET @row_number_b = -1;
SELECT a.id, a.type, a.start, a.end, TIMEDIFF(CAST(a.start AS TIME), CAST(b.end AS TIME)) AS DIFF
FROM
(SELECT (@row_number_a:=@row_number_a + 1) AS num, id, type, start, end
FROM tbl) a
LEFT JOIN (
SELECT (@row_number_b:=@row_number_b + 1) AS num, id, type, start, end
FROM tbl
) b
ON a.num = b.num
Result:
"id" "type" "start" "end" "DIFF"
"xxx" "YYY" "03:57" "03:59" "00:02:00"
"xxx" "ZZZ" "03:53" "03:55" "00:04:00"
"xxx" "ZZZ" "03:46" "03:49" \N
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.