在MySQL數(shù)據(jù)庫中,當需要對大量數(shù)據(jù)進行遞歸父級匯總時,可以采取以下方法:
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存儲過程實現(xiàn)了遞歸父級匯總。通過每次只處理1000條記錄,避免了一次處理大量數(shù)據(jù)造成的性能問題。