mysql - 如何在 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
但这不是我需要的,如果您需要一些示例数据,请随时告诉我,非常感谢您的任何提前。
解决方案
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
.
推荐阅读
- android - EVP_CipherInit_ex 在未使用时崩溃,在解密密码时
- javascript - XMLHttpRequest onreadystatechange 在 Firefox 上不起作用
- java - Direct conversion from Collection
to LongStream - python - Django密码哈希使用函数password_hash()的php格式
- graphql - 使用内部查询的 GraphQL 突变插入
- python-3.x - 无法访问我的对象项目的原因
- email - 将 ansible 作业输出作为电子邮件发送
- php - 致命错误:未捕获的 ReflectionException:类配置不存在
- apache-kafka - 如何使用来自服务器的带有偏移值的 kafka 消息?
- python-3.x - 尝试连接到 vTiger 时凭据无效