sql - merging two sets of data and figuring out which is new and which is old -


i have 2 sets of data same fields:

+----+---------+-------------+ | pk | mycdkey | datecreated | +----+---------+-------------+ |  1 |  131048 | 8/18/2014   | |  2 |  131049 | 8/18/2014   | |  3 |  131050 | 8/18/2014   | |  4 |  131051 | 8/18/2014   | |  5 |  131052 | 8/18/2014   | |  6 |  131053 | 8/18/2014   | |  7 |  131054 | 8/18/2014   | |  8 |  131055 | 8/18/2014   | |  9 |  131058 | 8/18/2014   | | 10 |  131059 | 8/18/2014   | +----+---------+-------------+ 

and

+----+---------+-------------+ | pk | mycdkey | datecreated | +----+---------+-------------+ | 11 |  131048 | 8/19/2014   | | 12 |  131049 | 8/19/2014   | | 13 |  131053 | 8/19/2014   | | 14 |  131054 | 8/19/2014   | | 15 |  131055 | 8/19/2014   | | 16 |  131058 | 8/19/2014   | | 17 |  131059 | 8/19/2014   | | 18 |  111111 | 8/19/2014   | | 19 |  222222 | 8/19/2014   | | 20 |  333333 | 8/19/2014   | +----+---------+-------------+ 

the output have this:

+----+---------+------------+ | pk | mycdkey | delete/add | +----+---------+------------+ |  3 |  131050 | delete     | |  4 |  131051 | delete     | |  5 |  131052 | delete     | | 18 |  111111 | add        | | 19 |  222222 | add        | | 20 |  333333 | add        | +----+---------+------------+ 

the output shows me when comparing 2 dates, recent actions 3 of cds deleted , 3 added.

is there out of box way perhaps merge function?

thank @linger pointing out should explain how know added/deleted.

added: if mycdkey exists in recent date, not previous date, added.

deleted: if mycdkey exists in previous date, not in recent

please note when comparing 2 data sets, have 2 dates (as in example here have 8/18 , 8/19)

sql fiddle:

select m1.pk, m1.mycdkey, 'delete' `delete/add` mytable1 m1  m1.mycdkey not in  (    select t2.mycdkey    mytable2 t2 ) union select m2.pk, m2.mycdkey, 'add' `delete/add` mytable2 m2 m2.mycdkey not in  (    select t1.mycdkey    mytable1 t1 ); 

or (sql fiddle):

select m1.pk, m1.mycdkey, 'delete' `delete/add` mytable1 m1  left join mytable2 m2 on m1.mycdkey = m2.mycdkey  m2.mycdkey null union select m2.pk, m2.mycdkey, 'add' `delete/add` mytable1 m1  right join mytable2 m2 on m1.mycdkey = m2.mycdkey  m1.mycdkey null 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -