首页 > 解决方案 > 如何在 MySQL 中插入没有主键的 2 个表中的记录?

问题描述

如何在 MySQL 中插入没有主键的 2 个表中的记录?

我想table_a用下面的sql插入:

insert into table_a select 
tc.id, tc.code,tb.name,tb.sordid,tb.others
from table_b tb 
left join table_c tc
on sb.code = spir.code

但是上面的SQL会报主键错误(table_c.id = table_a.id are primary key ),我只能用下面的SQL

insert into table_a select 
tc.id, tc.code,tb.name,tb.sordid,tb.others
from table_b tb 
left join table_c tc
on sb.code = spir.code where tc.id is not null

表_a

id   code  name     sortid  others
-----------------------------------
1     abc  ASDAG     1      sfgsdf
1     abc   asgasd    2      asd
1     abc  asdgasd  3      sfgsdf
1     abc   asdgas    4      asd
2     ad  ASDAG     1      sfgsdf
2     ad   sd       2       asd
2     ad  sss       3     sfgsdf
3     adcs  ASDAG     1      sfgsdf
3     adcs   sd       2       asd

表_b

id   code  name     sortid  others
-----------------------------------
99     abc   asgasd    1      asd
99     abc  asdgasd    2      sfgsdf
6      ad  ASDAG       1      sfgsdf

表_c

id   code
----------
 1    abc
 2    ad
 3   adcs

但这不是我需要的,如果您需要一些示例数据,请随时告诉我,非常感谢您的任何提前。

标签: mysqlsqlinsertprimary-key

解决方案


MySQL 提供了两种方法来避免在这种情况下插入行:

insert into table_a
    select tc.id, tc.code,tc.name,tb.sordid,tb.others
    from table_b tb left join
         table_c tc
         on sb.code = spir.code
    where tc.id is not null
    on duplicate key update id = values(id);

注意:这通过不插入行来避免错误。我不确定这是否是你真正想要的。

您也可以使用insert ignore.


推荐阅读