I have a question about SQL, especially SQLite3. I have two tables, let's name them main_table
and temp_table
. These tables are based on the same relational schema so they have the same columns but different rows (values).
Now what I want to do:
For each row of the main_table
I want to replace it if there is a row in a temp_table
with the same ID. Otherwise I want to keep the old row in the table.
I was thinking about using some joins
but it does not provides the thing I want.
Would you give me an advice?
EDIT: ADITIONAL INFO:
I would like to avoid writing all columns because those tables conains tens of attributes and since I have to update all columns it couldn't be necessary to write out all of them.
If the tables have the same structure, you can simply use SELECT *
:
BEGIN;
DELETE FROM main_table
WHERE id IN (SELECT id
FROM temp_table);
INSERT INTO main_table
SELECT * FROM temp_table;
COMMIT;
(This will also add any new rows in temp_table
that did not previously exist in main_table
.)
You have 2 approaches:
Update current rows inside main_table
with data from temp_table
. The relation will be based by ID.
Add a column to temp_table
to mark all rows that have to be transferred to main_table
or add aditional table to store IDs
that have to be transferred. Then delete all rows that have to be transferred from table main_table
and insert corresponding rows from temp_table
using column with marks or new table.
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.