Mysql从一个表中选择记录并添加到表2中,将最后插入的ID更新到table1中

时间:2017-10-03 13:46:55

标签: mysql sql mysqli

我有两个不同的表tbl_addresstbl_support。我想从addresspostcod选择tbl_supportinsert e到tbl_address,然后在update address_id中选择tbl_support id上次插入tbl_address = id, address, postcode, country. tbl_support = id, address_id ,name, address,postcode, 的{​​1}}。我该如何撰写查询。

{{1}}

2 个答案:

答案 0 :(得分:0)

如果地址表autoincrement中的列id字段尝试:

   insert into tbl_address select address, postcode from tbl_support;

然后,如果地址和邮政编码是唯一的设置,您可以更新tbl_support。

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

答案 1 :(得分:0)

您需要执行两个单独的查询。首先在tbl_address表中插入所有tbl_support记录。然后你需要执行第二个查询,你可以通过匹配的tbl_address地址,邮政编码和tbl_support地址,邮政编码等来更新address_id。

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)