Suppose I have the following table A
:
create table A (
code-id integer primary key,
code-name-1 varchar(200) not null,
code-name-2 varchar(200) not null,
foreign key (code-id) references another-table(code-id)
);
And one more table, B
:
create table B (
code-id integer primary key,
code-name-1 varchar(200) not null,
code-name-2 varchar(200) not null,
foreign key (code-id) references another-table(code-id)
);
Both tables, A
and B
hold unique code-id
references into another-table
which is not relevant to the question.
Is it possible to write a single query that can identify in one fell swoop:
code-id
s are in A
but not in B
. code-id
s are in B
but not in A
. code-id
s are the same in A
and B
, but their code-name-1
or code-name-2
values are different (either of them). I believe that this could be solved by one left join
clause, with its results concatenated to a right join
clause, with its results concatenated to a third inner join
clause, enhanced with two string comparison predicates for the on
clause.
Am I on the right track?
Can I generate an additional column specifying the result of the operation? Eg column RESULT
with values ADDED
, REMOVED
, CHANGED
?
Is there a more clever way to specify this query, rather than having to concatenate three join
clauses?
Thanks!
In A but not in B
Select code-id from A
Except
Select code-id from B
In B but not in A
Select code-id from B
Except
Select code-id from A
In Both A and B
Select code-id from A
Intersect
Select code-id from B
As a single query, you should be able to UNION them Together
Select code-id from A
Except
Select code-id from B
UNION
Select code-id from B
Except
Select code-id from A
UNION
Select code-id from A
Intersect
Select code-id from B
You may use EXCEPT operand and one join like this
Select code-id, 'added' result from a
Except
Select code-id, 'added' result from b
Union all
Select code-id, 'removed' result from b
Except
Select code-id, 'removed' result from a
Union all
Select code-id, 'changed' result
from a join b on a.code-id = b.code-id
Where a.code-name-1 != b.code-name-1 or a.code-name-2 != b.code-name-2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.