MySQL将列数据从一个表复制到另一个表

时间:2014-03-30 06:27:27

标签: mysql insert

我正在使用phpmyadmin并尝试将address_id值从表address_book复制到表customertable(customers_default_billing_address_id

地址簿中列出了几百个地址,我需要在customers表中使用address_id。 customers表和address_book表中的customer_id都是相同的。我终于解决了没有错误但它返回0结果并将客户数量从314加倍到628.所以基本上它只是创建了除address_id之外的新数据空行。

INSERT into customers (`customers_default_billing_address_id`)
SELECT `address_book_id` FROM address_book
GROUP BY `customers_id`;

我也尝试了这个并获得了授权许可问题。

insert into customers.customers_default_billing_address_id
SELECT `address_book_id` FROM `address_book`
inner join customers
on customers.customers_id = address_book.customers_id;

然后我尝试了这个并且没有收到授权许可错误,但它像第一次尝试那样将customers表中的数据加倍。

insert into customers (`customers_default_billing_address_id`) SELECT `address_book_id`                  FROM `address_book` inner join customers on customers.customers_id=address_book.customers_id

实施例

Table customers       
---------------                                                          
customers_id | customers_default_billing_address_id
123            0

Table address_book
------------------
customers_id | address_id
123            3256

输出:

Table customers        
----------------                                                                
customers_id | customers_default_billing_address_id
123            3256

Table address_book
------------------
customers_id | address_id
123            3256

请注意,customers_default_billing_address_id中的0值已更新为address_id。

1 个答案:

答案 0 :(得分:0)

您需要UPDATE查询,而不是INSERT INTO

试试这个:

UPDATE customers INNER JOIN
       address_book ON address_book.customer_id=customers_customer_id
     SET customers.customers_default_billing_address_id=address_book.address_book_id