As I am new to the sqlite3 database, I want to merge two sqlite3 databases with same schema with uniqe keyword. But while merging if two entries from two databases are found to be same, then I want to merge the entry which has the latest time stamp.
For example I have two databases : 1. student_old.db 2. student_new.db
Schema for both DB is :
CREATE TABLE student (
'idx' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
'name' CHAR(32) NOT NULL,
'age' INTEGER NOT NULL default 0,
'lastUpdateDate' timestamp DATE DEFAULT (datetime('now','localtime')),
UNIQUE (name)
);
Entries for two dbs are :
student_old.db
sqlite3 student_old.db
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from student;
1|abcd|20|2015-03-01 00:32:29
2|efgh|22|2015-03-01 00:32:29
3|ijkl|24|2015-03-01 00:32:29
sqlite>
student_new.db
sqlite3 student_new.db
sqlite> select * from student;
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
1|abcd|28|2015-03-01 00:32:34
2|mnop|26|2015-03-01 00:32:34
3|qrst|27|2015-03-01 00:32:34
sqlite>
I am merging the student_new.db to student_old.db with the below query
sqlite3 student_old.db <<"EOF"
attach './student_new.db' as toMerge;
BEGIN;
insert or ignore into student (name, age,lastUpdateDate)
select name, age, lastUpdateDate from toMerge.student;
COMMIT;
.q
So after the merging I will get
sqlite3 student_old.db
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from student;
1|abcd|20|2015-03-01 00:32:29 ------>>>> I got the time stamp of student_old.db
2|efgh|22|2015-03-01 00:32:29
3|ijkl|24|2015-03-01 00:32:29
5|mnop|26|2015-03-01 00:32:34
6|qrst|27|2015-03-01 00:32:34
sqlite>
But I want to merge the entries of same record but with the latest time stamp. Something like this :
sqlite> select * from student;
1|abcd|20|2015-03-01 00:32:34 ------>>>> I want entry of latest time stamp for same record.
2|efgh|22|2015-03-01 00:32:29
3|ijkl|24|2015-03-01 00:32:29
5|mnop|26|2015-03-01 00:32:34
6|qrst|27|2015-03-01 00:32:34
sqlite>
Please let me know the query to merge the latest timestamp if I found the same records in two databases.
Your help would be highly appreciated.
Aucun commentaire:
Enregistrer un commentaire