code_junkie

querying 2 tables with the same spec for the differences

Nov 10th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. CREATE TABLE feed_tbl
  2. (
  3. code varchar(15),
  4. name varchar(40),
  5. status char(1),
  6. update char(1)
  7. CONSTRAINT feed_tbl_PK PRIMARY KEY (code)
  8.  
  9. CREATE TABLE data_tbl
  10. (
  11. code varchar(15),
  12. name varchar(40),
  13. status char(1),
  14. update char(1)
  15. CONSTRAINT data_tbl_PK PRIMARY KEY (code)
  16.  
  17. CREATE VIEW delta_vw AS (
  18. SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 0 as diff_type
  19. FROM feed_tbl LEFT OUTER JOIN
  20. data_tbl ON feed_tbl.code = data_tbl.code
  21. WHERE (data_tbl.code IS NULL)
  22.  
  23. UNION
  24.  
  25. SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 1 as diff_type
  26. FROM data_tbl RIGHT OUTER JOIN
  27. feed_tbl ON data_tbl.code = feed_tbl.code
  28. where (feed_tbl.name <> data_tbl.name) OR
  29. (data_tbl.status <> feed_tbl.status) OR
  30. (data_tbl.update <> feed_tbl.update)
  31.  
  32.  
  33. UNION
  34.  
  35. SELECT data_tbl.code, data_tbl.name, data_tbl.status, data_tbl.update, 2 as diff_type
  36. FROM feed_tbl LEFT OUTER JOIN
  37. data_tbl ON data_tbl.code = feed_tbl.code
  38. WHERE (feed_tbl.code IS NULL)
  39.  
  40. )
  41.  
  42. select dt.*
  43. from
  44. data_tbl dt
  45. ,(
  46. select code
  47. from
  48. (
  49. select * from feed_tbl
  50. union
  51. select * from data_tbl
  52. )
  53. group by code
  54. having count(*) > 1
  55. ) diffs --"diffs" will return all differences *except* those in the primary key itself
  56. where diffs.code = dt.code
  57. union --plus the ones that are only in feed, but not in data
  58. select * from feed_tbl ft where not exists(select code from data_tbl dt where dt.code = ft.code)
  59. union --plus the ones that are only in data, but not in feed
  60. select * from data_tbl dt where not exists(select code from feed_tbl ft where ft.code = dt.code)
Add Comment
Please, Sign In to add comment