select table1.Item, table1.Location, table1.Type,
table2.Item, table2.Location, table2.Type, table2.Sort,
table3.Item, table3.Location, table3.Type
from table1
full outer join table3
on table1.Item = table3.Item
and table1.Location = table3.Location
and table1.Type = table3.Type
full outer join table2
on (table1.Item = table2.Item
and table1.Location = table2.Location
and table1.Type = table2.Type
and table2.Sort = '2'
)
or (table3.Item = table2.Item
and table3.Location = table2.Location
and table3.Type = table2.Type
and table2.Sort = '2'
)
where (table2.Sort = '2' or table2.Sort is null)
rextester演示:http://rextester.com/MNW25175
結果
+------+----------+-------+------+----------+-------+------+------+----------+-------+
| Item | Location | Type | Item | Location | Type | Sort | Item | Location | Type |
+------+----------+-------+------+----------+-------+------+------+----------+-------+
| 123 | A | small | NULL | NULL | NULL | NULL | 123 | A | small |
| NULL | NULL | NULL | 123 | A | big | 2 | 123 | A | big |
| NULL | NULL | NULL | 123 | B | small | 2 | NULL | NULL | NULL |
+------+----------+-------+------+----------+-------+------+------+----------+-------+
這也適用,但只是因爲table2
有一個匹配的table1
所有行,這可能不適合你的實際使用情況:
select table1.Item, table1.Location, table1.Type,
table2.Item, table2.Location, table2.Type, table2.Sort,
table3.Item, table3.Location, table3.Type
from table1
full outer join table3
on table1.Item = table3.Item
and table1.Location = table3.Location
and table1.Type = table3.Type
full outer join table2
on table3.Item = table2.Item
and table3.Location = table2.Location
and table3.Type = table2.Type
and table2.Sort = '2'
where (table2.Sort = '2' or table2.Sort is null)
你在哪個RDMS上? – trincot
微軟SQL服務器 – dev
可以請你發表你的表格和代碼作爲格式文本,而不是圖像 – mansi