![](/img/trans.png)
[英]INSERT INTO table2 SELECT FROM table1 then UPDATE table1 rows that selected/inserted
[英]Mysql select record from one table and add into table 2, update last inserted ID into table1
我有两个不同的表tbl_address
和tbl_support
。 我想选择address
,从tbl_support
postcod
e insert
并insert
到tbl_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.