简体   繁体   English

根据外键复制几个mysql行

[英]copy several mysql rows based on foreign key

I want to copy several rows in a mysql table based on a foreign key, and asign the new rows a new foreign key ID.我想根据外键复制 mysql 表中的几行,并为新行分配一个新的外键 ID。 Assuming my table layout looks like this:假设我的表格布局如下所示:

test
-----
table1_id int(11)
value varchar(20)

How do I accomplish this?我该如何实现?

Found out that the query would need to look like this:发现查询需要如下所示:
INSERT INTO test (table1_id, value) (SELECT '2', value FROM test WHERE table1_id=1)

which would copy all rows with the foreign key ID '1' and assign the new rows with ID 2 instead.这将复制外键 ID 为“1”的所有行,并改为分配 ID 为 2 的新行。 If the table contains more rows you could add them or change order in the SELECT part, like this如果表包含更多行,您可以在 SELECT 部分添加它们或更改顺序,如下所示

...(SELECT row1, '{$new_id}', value, another_row FROM...

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

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