在MySQL數(shù)據(jù)庫(kù)中,當(dāng)需要對(duì)大量數(shù)據(jù)進(jìn)行遞歸父級(jí)匯總時(shí),可以采取以下方法:
CREATE PROCEDURE recursive_sum(IN parent_id INT, OUT sum_num FLOAT) BEGIN DECLARE done BOOLEAN DEFAULT FALSE; DECLARE cur_id INT; DECLARE cur_sum FLOAT; DECLARE cur_count INT DEFAULT 0; DECLARE cur CURSOR FOR SELECT id, num FROM your_table WHERE parent_id = parent_id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; SET sum_num = 0; OPEN cur; repeat FETCH cur INTO cur_id, cur_sum; IF NOT done THEN SET cur_count = cur_count + 1; IF cur_count< 1000 THEN -- 每次只處理1000條記錄 CALL recursive_sum(cur_id, cur_sum); SET sum_num = sum_num + cur_sum; END IF; END IF; until done END REPEAT; CLOSE cur; END
上述代碼使用MySQL存儲(chǔ)過(guò)程實(shí)現(xiàn)了遞歸父級(jí)匯總。通過(guò)每次只處理1000條記錄,避免了一次處理大量數(shù)據(jù)造成的性能問(wèn)題。