我的问题很简单。我有表sets
存储产品集(更多产品在外面看起来像一个 - 计算机,鼠标和键盘,例如)它使用sets_products
表到products
表连接M:N 。每个产品都可以有参数(再次连接M:N)。
我有一个程序,它将所有参数生成为字符串(对于搜索缓存 - 如'hdd:120GB,LCD:1440:900,..'),但现在我需要遍历集合的产品并调用该过程对于他们每个人。我不能用PHP做,因为它用于触发器。
我想使用这样的东西(伪SQL)
FOREACH(SELECT products_id FROM sets_products WHERE set_id = 1)
generate_parameter_list(product_id,@result)
@param = CONCAT(@param,",",@result);
END FOREACH;
这可以在MySQL中完成吗?
答案 0 :(得分:36)
这是mysql reference for cursors。所以我猜它是这样的:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
答案 1 :(得分:11)
这可以通过MySQL完成,尽管它非常不直观:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//