gpt4 book ai didi

sql - Postgresql:从多个表(具有相同字段)查看

转载 作者:行者123 更新时间:2023-12-04 01:29:00 25 4
gpt4 key购买 nike

我有以下数据库架构:

enter image description here

我想为所有属性类型(公寓、地 block 、房屋)创建带有地址字段、属性价格/大小和用户 ID 的 View 。

我有一个像这样的 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

这个脚本只为公寓创建 View ,它看起来不错,但我也想在我的 View 中显示房屋和地 block ,我不知道如何在 View 中放入我的价格列 - 所有属性表的价格值( plothouseflat)。如何在一个 View 中显示来自三个属性表的数据。我可以通过多选来实现吗?

最佳答案

您需要使用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

关于sql - Postgresql:从多个表(具有相同字段)查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61359553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com