Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy data between two tables in SQLite?

I have two table with different column like this:

table1
(
    _id,
    title,
    name,
    number,
    address
)

table2
(
    _id,
    phone,
    name,
    address
)

How can I copy data 'name', 'address' from table1 to table2.

And my question have two situation:

  • First: table1, table2 in the same database file
  • Second: table1 in data1.db file, table2 in data2.db file
like image 472
Dennie Avatar asked Oct 13 '09 12:10

Dennie


People also ask

How copy data from two tables to another table in SQL?

If you want to copy the data of one SQL table into another SQL table in the same SQL server, then it is possible by using the SELECT INTO statement in SQL. The SELECT INTO statement in Structured Query Language copies the content from one existing table into the new table.

How do I query two tables in SQLite?

To query data from multiple tables, you use INNER JOIN clause. The INNER JOIN clause combines columns from correlated tables. Suppose you have two tables: A and B. A has a1, a2, and f columns.

What does VACUUM do in SQLite?

The VACUUM command works by copying the contents of the database into a temporary database file and then overwriting the original with the contents of the temporary file. When overwriting the original, a rollback journal or write-ahead log WAL file is used just as it would be for any other database transaction.


1 Answers

Copying in SQL works like so:

insert into table2 (name, address)
select name, address
from table1

If the values of the column id_ are the same, you need to insert and update

insert into table2 (name, address)
select name, address
from table1 t1
where not exists (select * from table2 t2 where t1._id = t2._id)
;
update table2 t2 name = (select name from table1 t2 where t1._id = t2._id)
;
update table2 t2 address = (select address from table1 t2 where t1._id = t2._id)

If you need to copy the columns between databases, you first export them into a file (use any format you like, for example CSV) and then merge that file into the second database manually since you can't write an SQL which says "use these sqlite structures".

like image 71
Aaron Digulla Avatar answered Oct 21 '22 03:10

Aaron Digulla