简体   繁体   English

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

[英]How to insert many unique rows via INSERT in mysql?

You know, you can duplicate an entry in a table like so; 您知道,可以像这样在表中复制一个条目。

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

..where my primary key "id" is an auto_increment integer ..其中我的主键“ id”是一个auto_increment整数

My question is, is there a way to create ... say 10 entries in a similar way, without using a loop in my php script. 我的问题是,有没有一种方法可以创建...说10个条目, 而无需在我的php脚本中使用循环。 Maybe a loop in mysql? 也许在MySQL循环?

thanks for help 感谢帮助

UPDATE UPDATE

It should insert the same column 10 times. 它应该在同一列中插入10次。

If you wish to insert 10 records with the same conditions: 如果您希望插入10条具有相同条件的记录:

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

And with another conditions: 还有其他条件:

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

And in PHP if you queries are too complicated to use INSERT INTO ... SELECT , you can select required data, form a single bulk insert query and execute it: 在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);

No problem :) Select more than one tupel in your select statement. 没问题:)在您的选择语句中选择一个以上的小礼堂。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM