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等于1的记录中的bc,将结果转为秒记录到表A的ac字段 如果查询结果列表中,有bd等于1的结果且超过一条,跳过
时间: 2024-03-12 22:44:10 浏览: 56
mysql实用技巧之比较两个表是否有不同数据的方法分析
好的,根据您的要求,我已经理解了您的问题。以下是存储过程的代码:
```
DELIMITER $$
CREATE PROCEDURE update_ac()
BEGIN
DECLARE ac_val INT;
DECLARE aa_val VARCHAR(255);
DECLARE bb_val VARCHAR(255);
DECLARE bc_val DATETIME;
DECLARE bd_val INT;
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT aa FROM tableA WHERE ac IN (3, 4, 5);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO aa_val;
IF done THEN
LEAVE read_loop;
END IF;
SELECT bb, bc, bd INTO bb_val, bc_val, bd_val FROM tableB WHERE ba = aa_val;
DECLARE bd1_count INT;
DECLARE bd2_count INT;
DECLARE bd5_bc_diff INT DEFAULT 0;
DECLARE bd1_bc_diff INT DEFAULT 0;
SELECT COUNT(*) INTO bd1_count FROM tableB WHERE ba = aa_val AND bd = 1;
SELECT COUNT(*) INTO bd2_count FROM tableB WHERE ba = aa_val AND bd = 2;
IF bd1_count = 0 THEN
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 0))) INTO bd5_bc_diff;
UPDATE tableA SET ac = bd5_bc_diff WHERE aa = aa_val;
ELSEIF bd1_count = 1 THEN
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 0))) INTO bd5_bc_diff;
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 1))) INTO bd1_bc_diff;
UPDATE tableA SET ac = bd5_bc_diff - bd1_bc_diff WHERE aa = aa_val;
END IF;
IF bd1_count > 1 THEN
CONTINUE;
END IF;
IF bd1_count = 1 AND bd2_count > 0 THEN
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 0))) INTO bd5_bc_diff;
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 1))) INTO bd1_bc_diff;
DECLARE cur2 CURSOR FOR SELECT bc FROM tableB WHERE ba = aa_val AND bd = 2;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur2;
read_loop2: LOOP
FETCH cur2 INTO bc_val;
IF done THEN
LEAVE read_loop2;
END IF;
SELECT TIMESTAMPDIFF(SECOND, bc_val, (SELECT bc FROM tableB WHERE ba = aa_val AND bd = 0))) INTO bd5_bc_diff;
SET bd1_bc_diff = bd1_bc_diff - bd5_bc_diff;
END LOOP;
CLOSE cur2;
UPDATE tableA SET ac = bd5_bc_diff - bd1_bc_diff + bd1_bc_diff WHERE aa = aa_val;
END IF;
END LOOP;
CLOSE cur;
END$$
DELIMITER ;
```
请将此代码复制到 MySQL 客户端中并执行即可。注意,这只是一个初步的实现,可能需要根据您的具体需求进行调整。
阅读全文