Postgresql:从多个表(具有相同字段)查看
Postgresql: view from multiple tables (with same fields)
我有以下数据库模式:
我想为所有 属性 类型(公寓、地块、房屋)创建带有地址字段、属性 price/size 和用户 ID 的视图。
我有一个这样的 sql 脚本:
create or replace VIEW auction_view3 AS
select ROW_NUMBER() OVER(ORDER BY f.userid) AS id, f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor
FROM address a, flat f, realassets r
WHERE f.addressid = a.id AND a.realassetid =r.id
这个脚本只为公寓创建视图,它看起来不错,但我也想在我的视图中显示房屋和地块,我不知道如何在视图中放入我的价格列 - 所有 属性 表(plot
、house
、flat
)。
如何在一个视图中显示来自三个 属性 表的数据。
我可以通过多选来实现吗?
您需要使用 union
,就像在普通 select
查询中一样:
create or replace view auction_view3 as
select row_number() over(order by f.userid) as id, f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor
from address a, flat f, realassets r
where f.addressid = a.id and a.realassetid =r.id
union all
select row_number() over(order by p.userid) as id, p.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, p.price, p."size", p.rooms, p.floor
from address a, plot p, realassets r
where p.addressid = a.id and a.realassetid =r.id
union all
select row_number() over(order by h.userid) as id, h.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, h.price, h."size", h.rooms, h.floor
from address a, house h, realassets r
where h.addressid = a.id and a.realassetid =r.id
此处 union all
速度很快但不会删除重复项,如果您不想删除它们 - 请改用 union
。
我有以下数据库模式:
我想为所有 属性 类型(公寓、地块、房屋)创建带有地址字段、属性 price/size 和用户 ID 的视图。
我有一个这样的 sql 脚本:
create or replace VIEW auction_view3 AS
select ROW_NUMBER() OVER(ORDER BY f.userid) AS id, f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor
FROM address a, flat f, realassets r
WHERE f.addressid = a.id AND a.realassetid =r.id
这个脚本只为公寓创建视图,它看起来不错,但我也想在我的视图中显示房屋和地块,我不知道如何在视图中放入我的价格列 - 所有 属性 表(plot
、house
、flat
)。
如何在一个视图中显示来自三个 属性 表的数据。
我可以通过多选来实现吗?
您需要使用 union
,就像在普通 select
查询中一样:
create or replace view auction_view3 as
select row_number() over(order by f.userid) as id, f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor
from address a, flat f, realassets r
where f.addressid = a.id and a.realassetid =r.id
union all
select row_number() over(order by p.userid) as id, p.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, p.price, p."size", p.rooms, p.floor
from address a, plot p, realassets r
where p.addressid = a.id and a.realassetid =r.id
union all
select row_number() over(order by h.userid) as id, h.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, h.price, h."size", h.rooms, h.floor
from address a, house h, realassets r
where h.addressid = a.id and a.realassetid =r.id
此处 union all
速度很快但不会删除重复项,如果您不想删除它们 - 请改用 union
。