0

给定书号 id和书本数,我想在表格中插入与书本一样多的行这是我的非工作解决方案:

DROP PROCEDURE IF EXISTS insert_into_book_copy_table;
CREATE PROCEDURE insert_into_book_copy_table (IN in_book_id INT,
                                              IN in_num     INT)
BEGIN

    SET @I = 1;
    SET @ACQUIRED = CURRENT_TIMESTAMP;

    WHILE I <= in_num DO 
        INSERT INTO book_copy (book_id, acquired) # The table has an
        VALUES (in_book_id, @ACQUIRED);           # auto-increment field
                                                  # which I didn't list here
        SET @I = @I + 1;
    END WHILE;

END$$

例如,如果给定的书号 id是 23 并且书本的数量等于 8,那么book_copy 表应该如下所示:

SELECT * FROM book_copy;
╔══════════════╦══════════╦═════════════════════╗
║ book_copy_id ║  book_id ║      acquired       ║
╠══════════════╬══════════╬═════════════════════╣
║            1 ║       23 ║ 2013-04-15 18:15:20 ║
║            2 ║       23 ║ 2013-04-15 18:15:20 ║
║            3 ║       23 ║ 2013-04-15 18:15:20 ║
║            4 ║       23 ║ 2013-04-15 18:15:20 ║
║            5 ║       23 ║ 2013-04-15 18:15:20 ║
║            6 ║       23 ║ 2013-04-15 18:15:20 ║
║            7 ║       23 ║ 2013-04-15 18:15:20 ║
║            8 ║       23 ║ 2013-04-15 18:15:20 ║
╚══════════════╩══════════╩═════════════════════╝

有没有更好的编码方式?

4

1 回答 1

2

试试这个,作为一个单一的 SQL 语句:-

INSERT INTO book_copy (book_id, acquired)
SELECT a.i+b.i*10+c.i*100 + 1, $BookId, NOW()
FROM integers a, integers b, integers c
WHERE a.i+b.i*10+c.i*100 < $NumberToInsert

依赖于一个包含 10 行的单列(称为 i)的整数表,其值为 0 到 9。将其与自身连接两次会给出从 0 到 999 的所有数字(可以轻松扩展),因此最多可以插入一份声明中包含 1000 本书。

编辑 - 如果你不想创建一个整数表,那么你可以用几个返回常量的子查询来做同样的事情: -

INSERT INTO book_copy (book_id, acquired)
SELECT a.i+b.i*10+c.i*100 + 1, $BookId, NOW()
FROM (SELECT 0 AS i UNION SELECT 1 AS i UNION SELECT 2 AS i UNION SELECT 3 AS i UNION SELECT 4 AS i UNION SELECT 5 AS i UNION SELECT 6 AS i UNION SELECT 7 AS i UNION SELECT 8 AS i UNION SELECT 9 AS i ) a,
(SELECT 0 AS i UNION SELECT 1 AS i UNION SELECT 2 AS i UNION SELECT 3 AS i UNION SELECT 4 AS i UNION SELECT 5 AS i UNION SELECT 6 AS i UNION SELECT 7 AS i UNION SELECT 8 AS i UNION SELECT 9 AS i ) b,
(SELECT 0 AS i UNION SELECT 1 AS i UNION SELECT 2 AS i UNION SELECT 3 AS i UNION SELECT 4 AS i UNION SELECT 5 AS i UNION SELECT 6 AS i UNION SELECT 7 AS i UNION SELECT 8 AS i UNION SELECT 9 AS i ) c
WHERE a.i+b.i*10+c.i*100 < $NumberToInsert
于 2013-04-15T15:06:50.577 回答