简体   繁体   中英

MySQL copy colmn data from one table to another row

I am using phpmyadmin and trying to copy the address_id values from table address_book to the table customers row ( customers_default_billing_address_id )

There are a few hundred addresses listed in address book and I need the address_id in the customers table. Both the customer_id in the customers table and address_book table are the same. I finally got around to not having an error but it returned 0 results and doubled the amount of customers from 314 to 628. So basically it just created new rows of empty data except for address_id.

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

I also tried this and got grant permission problems.

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;

I then tried this and received no grant permission errors but it doubled the data in the customers table like the first attempt did.

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

Example

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

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

Output:

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

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

Notice the 0 value in customers_default_billing_address_id has been update to address_id.

You need an UPDATE query, not INSERT INTO .

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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