I have two tables, same structure (filename, filesize, permissions), and possible different or missing values between the two..
I would like to display all the records with the following fields:
filename | filesizeTable1 | permissionsTable1| filesizeTable2 | permissionsTable2 | match
and I would like:
- the same filename to be displayed only once
- if filename is missing in one of the two tables, the columns filesize and permissions for that table would be empty
- if filename exists on both tables, but one of the other fields is different the field "match" would display "1"
- if filename exists on both tables, and the other fields are the same, the field "match" would display "0"
The step 1 is achievable with a join between the two tables (select filename from table1 union select filename from table2 order by filename;) but I'm stuck on how to proceed to have empty lines when a filename is missing in one of the two tables..
Solution (thanks Lennart):
select a.filename as filename
, a.size as filesize1, a.permissions as permissions1
, b.size as filesize2, b.permissions as permissions2
, CASE
WHEN a.filename IS NULL or b.filename IS NULL THEN 1
WHEN a.size != b.size THEN 2
WHEN a.permissions != b.permissions THEN 2
ELSE 0
END as Match
from scanTableHost1 as a
LEFT JOIN scanTableHost2 as b
ON a.filename = b.filename
UNION
select b.filename as filename
, a.size as filesize1, a.permissions as permissions1
, b.size as filesize2, b.permissions as permissions2
, CASE
WHEN a.filename IS NULL or b.filename IS NULL THEN 1
WHEN a.size != b.size THEN 2
WHEN a.permissions != b.permissions THEN 2
ELSE 0
END as Match
from scanTableHost2 as b
LEFT JOIN scanTableHost1 as a
ON a.filename = b.filename
FULL
joins?scanTableHostx
. If so you the left table can never be null, so you can simplify your first CASE to:WHEN b.filename IS NULL THEN 1
and the second one to:WHEN a.filename IS NULL IS NULL THEN 1
. Also!=
works in many DBMS, but the standard operator for not equals in SQL is<>
1
, the code says2
.