mysql update based on time stamp in another column

Sr New :
+------+------+--------------------+--------------------+----------+
| SEQ  | ID   |instamp         |outstamp        | duration |
+------+------+--------------------+--------------------+----------+
| 2516 |    1 |2020-02-22 14:22:47 |2020-02-22 14:24:06 |     NULL |
| 2517 |    1 |2020-02-22 14:24:08 |2020-02-22 14:24:27 |     NULL |
| 2518 |    1 |2020-02-22 14:24:28 |2020-02-22 14:24:47 |     NULL |
| 2519 |    1 |2020-02-22 14:24:48 |2020-02-22 14:25:06 |     NULL |
| 2520 |    1 |2020-02-22 14:25:08 |2020-02-24 23:14:00 |     NULL |

I am trying to update the last duration parameter. if I do

"mysql> SELECT TIMESTAMPDIFF(MINUTE,outTimestamp,intimestamp) from sTable;

This is working. but I am not able to update the last column.

I tried

update sTable rt set duration = (select TIMESTAMPDIFF(MINUTE, outstamp,instamp) from sTable rt1 where rt1.outstamp is not null and rt.seq = rt1.seq) ;

This is giving an error. can you please let me know if I am missing anything.

nbk :

You Update clause it not correct. It must be

UPDATE sTable rt SET duration = TIMESTAMPDIFF(MINUTE, outstamp,instamp) 
WHERE rt.outstamp IS NOT nulL;
CREATE TABLE sTable (
  `SEQ` INTEGER,
  `ID` INTEGER,
  `instamp` datetime,
  `outstamp` datetime,
  `duration` INTEGER 
);
INSERT INTO sTable
  (`SEQ`, `ID`, `instamp`, `outstamp`, `duration`)
VALUES
  ('2516', '1', '2020-02-22 14:22:47', '2020-02-22 14:24:06', NULL),
  ('2517', '1', '2020-02-22 14:24:08', '2020-02-22 14:24:27', NULL),
  ('2518', '1', '2020-02-22 14:24:28', '2020-02-22 14:24:47', NULL),
  ('2519', '1', '2020-02-22 14:24:48', '2020-02-22 14:25:06', NULL),
  ('2520', '1', '2020-02-22 14:25:08', '2020-02-24 23:14:00', NULL);
SELECT TIMESTAMPDIFF(MINUTE,outstamp,instamp) from sTable;
| TIMESTAMPDIFF(MINUTE,outstamp,instamp) |
| -------------------------------------: |
|                                     -1 |
|                                      0 |
|                                      0 |
|                                      0 |
|                                  -3408 |
update sTable rt set duration = TIMESTAMPDIFF(MINUTE, outstamp,instamp) 
where rt.outstamp is not null ;
SELECT * FROM sTable;
 SEQ | ID | instamp             | outstamp            | duration
---: | -: | :------------------ | :------------------ | -------:
2516 |  1 | 2020-02-22 14:22:47 | 2020-02-22 14:24:06 |       -1
2517 |  1 | 2020-02-22 14:24:08 | 2020-02-22 14:24:27 |        0
2518 |  1 | 2020-02-22 14:24:28 | 2020-02-22 14:24:47 |        0
2519 |  1 | 2020-02-22 14:24:48 | 2020-02-22 14:25:06 |        0
2520 |  1 | 2020-02-22 14:25:08 | 2020-02-24 23:14:00 |    -3408

db<>fiddle here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21289&siteId=1