我在mysql中有一个存储过程,语法如下:
insert into tbl1 (p1, p2) values (p2, p3);
set inserted_id = last_insert_id();
insert into tbl2 (id, image) values (inserted_id, 'list_of_image');
现在我不知道如何为此插入分隔此图像列表(没有固定计数)。 任何想法?
答案 0 :(得分:1)
假设'list_of_image'
是一个包含逗号分隔值的字符串,您可以使用纯SQL执行
DELIMITER $$
CREATE PROCEDURE sp_insert_images(IN p3 VARCHAR(64), IN p4 VARCHAR(64), IN images VARCHAR(512))
BEGIN
INSERT INTO Table1 (p1, p2)
VALUES (p3, p4);
INSERT INTO Table2 (id, image)
SELECT LAST_INSERT_ID(), SUBSTRING_INDEX(SUBSTRING_INDEX(i.images, ',', n.n), ',', -1) image
FROM
(
SELECT images images
) i CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
ORDER BY n
) n
WHERE n.n <= 1 + (LENGTH(i.images) - LENGTH(REPLACE(i.images, ',', '')));
END$$
DELIMITER ;
致电您的SP
CALL sp_insert_images('Some value1', 'Some value2', 'image1, image2, image3');
这是 SQLFiddle 演示。
注意:
n
)来生成一系列数字。