Home > database >  How MySQL table of tree structure sum?
How MySQL table of tree structure sum?

Time:09-26

A table is as follows:
 DROP TABLE IF the EXISTS ` t_test `; 
The CREATE TABLE ` t_test ` (
` Id ` int (11) NOT NULL,
` ParentId ` int (11) NULL DEFAULT NULL,
` Qty ` int (11) NULL DEFAULT NULL,
` Qty_Sum ` int (11) NULL DEFAULT NULL,
PRIMARY KEY (` Id `) USING BTREE
) ENGINE=InnoDB CHARACTER SET=utf8 COLLATE=utf8_general_ci ROW_FORMAT=Compact;

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
- Records of t_test
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
INSERT INTO ` t_test ` VALUES (1, 0, 1, 0);
INSERT INTO ` t_test ` VALUES (2, 1, 2, 0);
INSERT INTO ` t_test ` VALUES (3, 2, 3, 0);
INSERT INTO ` t_test ` VALUES (4, 3, 4, 0);
INSERT INTO ` t_test ` VALUES (5, 1, 5, 0);

The SET FOREIGN_KEY_CHECKS=1;

Hope to be able to in a flexible way to find the tree structure (hierarchy multi-stage uncertainty) of each level, and achieve results in the table below (Qty_Sum as the summation of the results) :
 
Id ParentId Qty Qty_Sum
1 0 1 15
2 1 2 9
3, 2, 3, 7
4, 3, 4, 4
5 1 5

  • Related