简体   繁体   中英

Mysql select record from one table and add into table 2, update last inserted ID into table1

I have two different tables tbl_address and tbl_support . I want to select address , postcod e from tbl_support and insert into into tbl_address and want to update address_id in tbl_support with last inserted id . How do I write query.

tbl_address = id, address, postcode, country.
tbl_support = id, address_id ,name, address,postcode,

if your column id field in address table autoincrement try this:

   insert into tbl_address select address, postcode from tbl_support;

then you can update tbl_support if address and postcode are unique set.

 update tbl_support s set s.address_id=(select id from tbl_address a where 
 a.address=s.address and a.postcode = s.postcode) 

you need to execute to two separate queries. first you insert all tbl_support record in tbl_address table.then you need to execute second query where you update address_id through a matching tbl_address address,postcode and tbl_support address, zip code.like below query.

INSERT INTO tbl_address ( 
      address, 
      postcode) 
SELECT address, 
       postcode 
FROM `tbl_support`;

UPDATE `tbl_support` SET address_id = (SELECT id FROM `tbl_address` 
WHERE  tbl_support.address= tbl_address.address 
AND tbl_support.postcode= tbl_address.postcode)

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