我必须在一个表中插入从另一个表中选择的记录,然后(然后)使用为后者生成的id更新前一个表。我该怎么办?
E.g。
input_table:
input_table: code new_id
aa NULL
bb NULL
output_table: id(auto_increment) code
... ...
SQL:
INSERT INTO output_table (code) SELECT code FROM input_table;
UPDATE input_table "WITH THE NEW IDS"
结果:
input_table: code new_id
aa 100
bb 101
output_table: id code
... ...
100 aa
101 bb
由于多种原因,我无法依赖code
中output_table
的唯一性。
任何提示?
答案 0 :(得分:1)
set @max_orig_id = coalesce((select max(id) from output_table),0);
insert into output_table (code) select code from input_table;
update input_table join output_table on input_table.code=output_table.code and output_table.id > @max_orig_id set input_table.new_id=output_table.id;
答案 1 :(得分:1)
我不认为上面的答案是多用户安全的。如果您必须具有并发访问权限,我建议放弃自动增量并使用您自己的ID序列。遗憾的是,MySQL缺少CREATE SEQUENCE
,但你可以模拟一个由隐藏的最后一个值表支持的函数。 (不要忘记在函数期间完全锁定表,以便多个用户获得不同的ID。)然后从函数中获取新的ID号,将其提供给INSERT
和UPDATE
语句。
有些方言支持INSERT ... RETURNING <column value>
,但MySQL不支持。{/ p>