select v1.ClothingID, v2.ClothingID as ClothingID2, v1.Shoes, v2.Shoes as Shoes2,
v1.Shirts, v2.Shirts as Shirts2
from (
select *, row_number() OVER (ORDER BY ClothingID) AS row
from view_1
) v1
full outer join (
select *, row_number() OVER (ORDER BY ClothingID) AS row
from view_2
) v2 on v1.row = v2.row
我认为使用新的不相关列 row 连接表的 full outer join 可以完成这项工作。
row_number() 存在于PostgreSQL 8.4 and above。
如果你有低版本你可以模仿row_number,例子如下。只有ClothingID 在视图范围内是唯一的,它才会起作用。
select v1.ClothingID, v2.ClothingID as ClothingID2, v1.Shoes, v2.Shoes as Shoes2,
v1.Shirts, v2.Shirts as Shirts2
from (
select *, (select count(*) from view_1 t1
where t1.ClothingID <= t.ClothingID) as row
from view_1 t
) v1
full outer join (
select *, (select count(*) from view_2 t2
where t2.ClothingID <= t.ClothingID) as row
from view_2 t
) v2 on v1.row = v2.row
在评论后添加:
我注意到并纠正了前面查询中的错误。
我会试着解释一下。首先,我们必须在两个视图中添加一个行号,以确保 id 中没有间隙。这是很简单的方法:
select *, (select count(*) from view_1 t1
where t1.ClothingID <= t.ClothingID) as row
from view_1 t
这包括两件事,简单的查询选择行(*):
select *
from view_1 t
和correlated subquery (read more on wikipedia):
(
select count(*)
from view_1 t1
where t1.ClothingID <= t.ClothingID
) as row
这对外部查询的每一行(这里是 (*))包括 self.因此,您可能会说计算所有具有ClothingID 小于或等于视图中每一行的当前行的行。对于唯一的ClothingID(我假设),它会为您提供行编号(按ClothingID 排序)。
data.stackexchange.com - row numbering 上的实时示例。
之后,我们可以使用两个带有行号的子查询来加入它们 (full outer join on Wikipedia),data.stackexchange.com - merge two unrelated views 上的实时示例。