how to get the difference between 2 tables in 2 different schema's in Oracle? [duplicate]
-
13-03-2021 - |
سؤال
I am using Oracle 11G.
I have a table called Tickets in the schema called 'tickets1" I have the same table structure in another schema called 'tickets2'
I want to find out
- What data is the same in both tables?
- What data is different?
CREATE TABLE tickets( ticket_number NUMBER NOT NULL, first_name VARCHAR2(50) NOT NULL, last_name VARCHAR2(50) NOT NULL, PRIMARY KEY(ticket_number) );
المحلول
To mustaccio's point, there's nothing particular about a schema that prevents you from querying objects from different schemas within the same query (putting privileges aside - since that's a function of security, not a unique feature of schemas).
So you can use a FULL JOIN
between the two tables across schemas with an appropriate WHERE
clause like so to answer your questions:
-- Gets all rows that have the same primary key (ticket_number) between the two tables
SELECT * -- Replace * with only the columns you need, as using * is generally bad practice
FROM tickets1.Tickets T1
FULL JOIN tickets2.Tickets T2
ON T1.ticket_number = t2.ticket_number
WHERE T1.ticket_number IS NOT NULL
AND T2.ticket_number IS NOT NULL
-- Gets all rows that have different primary keys (ticket_number) between the two tables
SELECT * -- Replace * with only the columns you need, as using * is generally bad practice
FROM tickets1.Tickets T1
FULL JOIN tickets2.Tickets T2
ON T1.ticket_number = t2.ticket_number
WHERE (T1.ticket_number IS NOT NULL AND T2.ticket_number IS NULL)
OR (T1.ticket_number IS NULL AND T2.ticket_number IS NOT NULL)
Note the above only compares the two tables by the primary key (ticket_number
). Depending on your definition of "same data" / "different data", you may want to compare by other fields in the tables as well.