如何在mysql中通过INSERT插入许多唯一的行?

时间:2012-03-23 08:53:45

标签: mysql

您知道,您可以像这样复制表格中的条目;

INSERT INTO `clubs`( `id_leagues`, `name`, `created`) SELECT id_leagues, name, created FROM clubs WHERE id = 36 LIMIT 1

..我的主键“id”是auto_increment integer

我的问题是,有没有办法创建...以类似的方式说出10个条目,没有在我的php脚本中使用循环。也许是mysql中的循环?

感谢您的帮助

更新

它应该插入相同的列10次。

2 个答案:

答案 0 :(得分:1)

如果您希望插入具有相同条件的10条记录:

INSERT INTO `clubs`( `id_leagues`, `name`, `created`) 
SELECT id_leagues, name, created FROM clubs WHERE id = 36 LIMIT 10

还有另一个条件:

INSERT INTO `clubs`( `id_leagues`, `name`, `created`) 
SELECT id_leagues, name, created FROM clubs WHERE id IN (36,37,38,40,45,55)

在PHP中,如果查询过于复杂而无法使用INSERT INTO ... SELECT,则可以选择所需数据,形成单个批量插入查询并执行它:

$query = "SELECT id_leagues, name, created FROM clubs WHERE id = 36 LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_NUM));
$data = array_fill(0, 9, "('".mysql_real_escape_string($row[0])."', '".mysql_real_escape_string($row[1])."', '".mysql_real_escape_string($row[2])."')");

$query = "INSERT INTO `clubs`( `id_leagues`, `name`, `created`) VALUES " . implode(',', $data);

mysql_query($query);

答案 1 :(得分:0)

没问题:)在select语句中选择多个元组。

INSERT INTO "table" ("col1", "col2", ...)
SELECT "col3", "col4", ...
FROM "table2"