繁体   English   中英

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

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

我有两个不同的表tbl_addresstbl_support 我想选择address ,从tbl_support postcod e insertinserttbl_address并希望使用最后插入的id update tbl_support address_id 我该如何写查询。

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

如果地址表中的列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) 

您需要执行两个单独的查询。 首先在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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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