简体   繁体   中英

SQL move row from one table to another with unmatched columns

I have found plenty of examples on how to insert into using a select then delete however,

I am looking to move data from one table to another and the columns ARE NOT matched for example

table1 ( id , location , lat , lon , date_added )

table2 ( id , location , lat , lon , date_added , requested )

essentially I would like to insert into table2 a row from table1 and add the $_SESSION['user_name'] to the requested field, and then delete the original row from the first table.

I have tried a few different things

$sql = "START TRANSACTION;
INSERT INTO bia_signs_pending (SELECT * FROM bia_signs WHERE id = ".$_GET['sign_id'].');

DELETE FROM bia_signs WHERE id = '          .$_GET['sign_id'].';
UPDATE bia_signs_pending SET requested='    .$_SESSION['user']['email'].
'WHERE id = '.$_GET['sign_id'].';
COMMIT;';

//this one breaks because the columns do not match

any suggestions?

You can use INSERT with column names

INSERT INTO TABLE2 (id, location, lat, lon, date_added)
SELECT id, location, lat, lon, date_added 
FROM table1 
WHERE ...

and you can add constants into an INSERT

INSERT INTO TABLE2 (id, location, lat, lon, date_added, requested)
SELECT id, location, lat, lon, date_added, 'Jonny'
FROM table1
WHERE ...

Just change your insert

INSERT INTO bia_signs_pending (SELECT FROM bia_signs WHERE id = ".$_GET['sign_id'].');

to

INSERT INTO bia_signs_pending (id, location, lat, lon, date_added) VALUES (SELECT * FROM bia_signs WHERE id = '".$_GET['sign_id'].');

Change your INSERT statement, add list of fields you are selecting:

INSERT INTO bia_signs_pending (id, location, lat, lon, date_added)
            SELECT * FROM bia_signs WHERE id = '{$_GET['sign_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