mysql 有两个表A、表B,其中表A有aa ab ac 三个字段,表B有bb ba bc bd四个字段,bc是datetime类型,表A的aa等于表B的ba。 写一个存储过程 获取表A中 ac等于3、4、和5的数据,遍历该结果集,根据表A的aa查询表B,得到多条表B的结果列表, 如果查询结果列表中,没有bd等于1的结果,将结果列表中 bd等于5的记录中的bc减去结果列表中 bd等于0的记录中的bc, 将结果转为秒记录到表A的ac字段。如果查询结果列表中,有bd等于1的结果, 将结果列表中 bd等于5的记录中的bc减去结果列表中(只有一条) bd等于0的记录中的bc(只有一条), 再减去 结果列表中所有bd等于2的记录中的bc,bd等于2的记录会有多条 再加上结果列表中所有bd等于1的记录中的bc,bd等于1的记录会有多条,将结果转为秒记录到表A的ac字段
时间: 2024-03-11 07:51:36 浏览: 58
mysql数据库创建学生表.zip
好的,下面是修改后的存储过程代码,它可以实现您的需求:
```
CREATE PROCEDURE update_ac()
BEGIN
DECLARE aa_val VARCHAR(255);
DECLARE ac_val INT;
DECLARE bb_val VARCHAR(255);
DECLARE bc_val DATETIME;
DECLARE bd_val INT;
DECLARE bd0_bc DATETIME;
DECLARE bd1_bc DATETIME;
DECLARE bd2_bc_sum INT DEFAULT 0;
DECLARE bd5_bc DATETIME;
DECLARE bd2_cursor CURSOR FOR SELECT bc FROM B WHERE ba = aa_val AND bd = 2;
DECLARE bd1_cursor CURSOR FOR SELECT bc FROM B WHERE ba = aa_val AND bd = 1;
DECLARE cur1 CURSOR FOR SELECT aa, ac FROM A WHERE ac IN (3,4,5);
DECLARE cur2 CURSOR FOR SELECT bb, bc, bd FROM B WHERE ba = aa_val;
OPEN cur1;
FETCH cur1 INTO aa_val, ac_val;
WHILE (aa_val IS NOT NULL) DO
SET bd0_bc = NULL;
SET bd1_bc = NULL;
SET bd2_bc_sum = 0;
SET bd5_bc = NULL;
OPEN cur2;
FETCH cur2 INTO bb_val, bc_val, bd_val;
WHILE (bb_val IS NOT NULL) DO
IF (bd_val = 0) THEN
SET bd0_bc = bc_val;
ELSEIF (bd_val = 1) THEN
SET bd1_bc = bc_val;
ELSEIF (bd_val = 2) THEN
SET bd2_bc_sum = bd2_bc_sum + TIME_TO_SEC(bc_val);
ELSEIF (bd_val = 5) THEN
SET bd5_bc = bc_val;
END IF;
FETCH cur2 INTO bb_val, bc_val, bd_val;
END WHILE;
CLOSE cur2;
IF (bd1_bc IS NULL) THEN
IF (bd5_bc IS NOT NULL) THEN
SET ac_val = TIME_TO_SEC(bd5_bc) - TIME_TO_SEC(bd0_bc);
END IF;
ELSE
OPEN bd2_cursor;
FETCH bd2_cursor INTO bc_val;
WHILE (bc_val IS NOT NULL) DO
SET bd2_bc_sum = bd2_bc_sum - TIME_TO_SEC(bc_val);
FETCH bd2_cursor INTO bc_val;
END WHILE;
CLOSE bd2_cursor;
OPEN bd1_cursor;
FETCH bd1_cursor INTO bc_val;
IF (bd0_bc IS NOT NULL AND bc_val IS NOT NULL) THEN
SET ac_val = TIME_TO_SEC(bd5_bc) - TIME_TO_SEC(bd0_bc) - TIME_TO_SEC(bc_val) + bd2_bc_sum;
END IF;
CLOSE bd1_cursor;
END IF;
UPDATE A SET ac = ac_val WHERE aa = aa_val;
FETCH cur1 INTO aa_val, ac_val;
END WHILE;
CLOSE cur1;
END
```
这个存储过程与之前的存储过程类似,不同之处在于处理bd等于2和bd等于1的记录时需要使用游标来遍历结果集并计算bc值的总和。此外,在计算ac值时需要使用所有bd等于1和bd等于2的记录。
阅读全文