简体   繁体   English

MySQL中插入命令中的Where子句

[英]Where clause in Insert command in mysql

I need to do something like this 我需要做这样的事情

insert into tableA(code) select code from tableB where id=tableB.id;

I cant insert the code until both id are matched. 在两个ID匹配之前,我无法插入代码。 How do i do this? 我该怎么做呢?

You can either do a join or use where exists like 您可以进行联接,也可以where exists使用

insert into tableA(code) 
select tb.code 
from tableB tb 
join tableA on tableA.id = tableB.id;

(OR) (要么)

insert into tableA(code) 
select tb.code 
from tableB tb where exists(select 1 from tableA 
where id = tb.id);

Looking at your comment, looks like you rather need a UPDATE statement like 查看您的评论,看起来您需要一个UPDATE语句,例如

UPDATE tableA a 
    JOIN tableB b ON a.id = b.id 
SET a.code = b.code;
INSERT INTO tableA.field1,tableA.field2,......
SELECT tableB.field1,tableB.field2,......
FROM tableB  
JOIN tableA ON tableA.id = tableB.id;

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

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