· 8 years ago · Aug 10, 2018, 05:08 AM
1CREATE PROCEDURE myproc
2BEGIN
3DECLARE CURSOR cur1 FOR SELECT id, price FROM table WHERE status=1;
4DECLARE CURSOR cur2 FOR SELECT id, price FROM table WHERE status=2;
5DECLARE CURSOR cur3 FOR SELECT id, price FROM table WHERE status=3;
6SET @done := 0;
7DECLARE CONTINUE HANDLER FOR NOT FOUND SET @done := 1;
8DROP TEMPORARY TABLE IF EXISTS combinations;
9CREATE TEMPORARY TABLE combinations (id INT, price DECIMAL(15,6)) ENGINE = Memory;
10cycle: WHILE 1
11 FETCH cur1 INTO @id1,@price1;
12 FETCH cur2 INTO @id2,@price2;
13 FETCH cur3 INTO @id3,@price3;
14 IF @done THEN
15 LEAVE cycle
16 END IF;
17 INSERT INTO combinations(id,price) VALUES (CONCAT_WS(',',@id1,@id2,@id3),@price1+@price2+@price3);
18END WHILE;
19CLOSE cur1;
20CLOSE cur2;
21CLOSE cur3;
22SELECT * FROM combinations;
23DROP TEMPORARY TABLE combinations;
24END;