I have this data and table structure,I am creating MySQL stored procedure to sum all the amount in the leftchild of the parentid, I don't have enough knowledge in stored procedure.and I need some help please because I'm lost.
CREATE TABLE IF NOT EXISTS `mytree` (
`parentid` int(11) NOT NULL,
`memberid` int(11) NOT NULL,
`position` char(1) NOT NULL,
`amount` decimal(10,2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `mytree` (`parentid`, `memberid`, `position`, `amount`) VALUES
(8, 27, 'R', 0.00),
(8, 28, 'L', 0.00),
(24, 26, 'R', 0.00),
(0, 1, '', 5500.00),
(24, 25, 'L', 0.00),
(21, 24, 'L', 500.00),
(21, 23, 'R', 0.00),
(18, 20, 'R', 1500.00),
(18, 19, 'L', 0.00),
(15, 18, 'R', 2000.00),
(15, 17, 'L', 0.00),
(13, 16, 'L', 0.00),
(13, 15, 'R', 2500.00),
(12, 14, 'R', 0.00),
(12, 13, 'L', 3000.00),
(10, 12, 'R', 3500.00),
(10, 11, 'L', 0.00),
(7, 10, 'R', 4000.00),
(7, 9, 'L', 0.00),
(5, 8, 'R', 500.00),
(5, 7, 'L', 4500.00),
(1, 6, 'R', 0.00),
(1, 5, 'L', 5500.00),
(20, 22, 'R', 0.00),
(20, 21, 'L', 1000.00);
here is my stored proc
CREATE DEFINER=`root`@`localhost` PROCEDURE `count_left_right_amount`(IN `p_memid` INT, OUT `tot_left_amount` DECIMAL(10,2))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE row_total decimal(10,2);
DECLARE total decimal(10,2);
DECLARE m_left int;
DECLARE run_left int;
DECLARE p_id int;
set total = 0;
select memberid into p_id from mytree where position = 'L' AND parentid = p_memid;
WHILE p_id != 0 DO
select amount into row_total from mytree where parentid = p_id
GROUP BY parentid;
select memberid into m_left from mytree where parentid = p_id;
set total = total + row_total;
set p_id = m_left;
END WHILE;
END
Example if the parentid is 5 ,so the leftchild is 7 then go down to his subtree sum it all,so the total amount in the left child is '22500'? please correct me if I'm wrong.
please help me.
Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire