问题描述
我正在学习MySQL,但遇到了问题。我有两个表.. table1和table2。
table1包含几列,例如(id,type,id_marca,price)等,而table2包含几列,例如(id,values,..,id_marca)。
我想要和想要做的是:
第一个表中的id_marca具有值,而第二个表中的id_marca具有NULL值。
我想将值从id_marca.table1复制到id_marca.table2。基本上将第一个表中的列复制到第二个表中。
I am learning MySQL and I have an issue. I have two tables.. table1 and table2.table1 contains several columns such as (id, type, id_marca, price) etc and table2 has several columns such as (id, values, .., id_marca).What I want and what I'm trying to do is:id_marca in the first table has values and the id_marca in the second table has NULL values.I want to copy the values from id_marca.table1 into id_marca.table2. Basically copy the column in the first table into the second one.
我用过
INSERT INTO table2 (id_marca) SELECT id_marca FROM table1 ;
但是问题出在下面。在插入后,它将列的值插入第一个表中
But the issue is the following.. it inserts the values of the column in the first table AFTER the NULL values and does not replace them.
要更好地看问题:
这是表1:
To see the issue better:This is table1:
id name id_marca
1 a 1
2 b 1
3 c 2
这是表2:
id value id_marca
1 123 NULL
2 34155 NULL
3 123 NULL
在我执行INSERT INTO之后table2(id_marca)从table1中选择id_marca,表2变为:
After I execute INSERT INTO table2 (id_marca) SELECT id_marca FROM table1 , table 2 becomes:
id value id_marca
1 123 NULL
2 34155 NULL
3 123 NULL
4 0 1
5 0 1
6 0 2
但我希望它是:
id value id_marca
1 123 1
2 34155 1
3 123 2
希望你会
推荐答案
您应该使用UPDATE而不是INSERT,并且如果这些表通过ID字段逻辑链接,那么尝试:
You should use UPDATE not INSERT and if these tables is logically linked by ID field then try:
UPDATE TABLE2 a
JOIN TABLE1 b ON a.id = b.id
SET a.id_marca = b.id_marca
这篇关于MySQL的。两张表,复制一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!