我在MySql中有这个数据集:
p_id c_id amount
5 1 2000
6 1 3000
7 1 4000
我需要在该表中插入相同的数据,只需将c_id计数器从 1 增加到 7。
因此,总共将有 21 个条目。
我怎样才能只用 SQL 做到这一点?
结果:
p_id c_id amount
5 1 2000
6 1 3000
7 1 4000
5 2 2000
6 2 3000
7 2 4000
5 3 2000
6 3 3000
7 3 4000
5 4 2000
6 4 3000
7 4 4000
c_id可以坚持到9点。
这是你想要的吗?
insert into t(p_id, c_id, amount)
select t.p_id, c.c_id, t.amount
from t cross join
(select 2 as c_id union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7
) c;
你需要的是一个序列生成器:在 MySQL 中生成整数序列
使用任何包含 7 行或更多行的表。
INSERT IGNORE INTO original_table
SELECT o.p_id, n.c_id, o.amount
FROM original_table o
JOIN (
SELECT @row := @row + 1 as c_id
FROM some_table t, (SELECT @row := 0) r
LIMIT 7
) n
ON true