mysql 表列复制_MySQL的。两张表,复制一列

bd96500e110b49cbb3cd949968f18be7.png

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.

I used

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.

To see the issue better:

This is table1:

id name id_marca

1 a 1

2 b 1

3 c 2

This is table2:

id value id_marca

1 123 NULL

2 34155 NULL

3 123 NULL

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

But I want it to be:

id value id_marca

1 123 1

2 34155 1

3 123 2

Hope you will understand, thank you in advance guys.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值