marți, 5 ianuarie 2010

[SQL] How to find out if two tables have the same elements

Considerations:
- The EXISTS condition is considered "to be met" if the subquery returns at least one row.
- The EXISTS condition can be used in any valid SQL statement - select, insert, update, or delete.
- The EXISTS condition can also be combined with the NOT operator.
- In order to see if 2 tables are the same:
-> (A-B) U (B-A) should be empty
-> also, we should consider duplicate values (that's why we are using a count(*) for values of the same type)

-- This will return all records from the student table where there are no records in the view_student table.
select s.ID, s.NAME, s.SPECIALIZATION, count(*) as COUNT_S
from student s
group by s.ID, s.NAME, s.SPECIALIZATION
where not exists
(select v.ID, v.NAME, v.SPECIALIZATION, count(*) as COUNT_S
from view_student v
group by v.ID, v.NAME, v.SPECIALIZATION
where s.ID = v.ID
and s.NAME = v.NAME
and s.SPECIALIZATION = v.SPECIALIZATION
and s.cnt = v.cnt)

union all

-- This will return all records from the view_student table where there are no records in the student table.
select v.ID, v.NAME, v.SPECIALIZATION, count(*) as COUNT_S
from view_student v
group by v.ID, v.NAME, v.SPECIALIZATION
where not exists
(select s.ID, s.NAME, s.SPECIALIZATION, count(*) as COUNT_S
from student s
group by s.ID, s.NAME, s.SPECIALIZATION
where s.ID = v.ID
and s.NAME = v.NAME
and s.SPECIALIZATION = v.SPECIALIZATION
and s.cnt = v.cnt)

Niciun comentariu:

Trimiteți un comentariu