简体   繁体   中英

mysql update based on time stamp in another column

+------+------+--------------------+--------------------+----------+
| 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.

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 );
\n \n
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);
\n \n
SELECT TIMESTAMPDIFF(MINUTE,outstamp,instamp) from sTable;
\n|  TIMESTAMPDIFF(MINUTE,outstamp,instamp) | \n|  -------------------------------------: | \n|  -1 | \n|  0 | \n|  0 | \n|  0 | \n|  -3408 | \n
update sTable rt set duration = TIMESTAMPDIFF(MINUTE, outstamp,instamp) where rt.outstamp is not null ;
\n \n
SELECT * FROM sTable;
\n SEQ | ID | instamp | outstamp | duration\n---: |  -: |  :------------------ |  :------------------ |  -------: \n2516 |  1 |  2020-02-22 14:22:47 |  2020-02-22 14:24:06 |  -1 \n2517 |  1 |  2020-02-22 14:24:08 |  2020-02-22 14:24:27 |  0 \n2518 |  1 |  2020-02-22 14:24:28 |  2020-02-22 14:24:47 |  0 \n2519 |  1 |  2020-02-22 14:24:48 |  2020-02-22 14:25:06 |  0 \n2520 |  1 |  2020-02-22 14:25:08 |  2020-02-24 23:14:00 |  -3408 \n

db<>fiddle here

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM