Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: view from multiple tables (with same fields)

I have following database schema:

enter image description here

I want to create view for all property types (flat,plot,house) with address fields, property price/size and user ID.

I have an sql script like this:

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 

This script create view only for flats, it looks good, but also I want to show houses and plots in my view, I don't know how to put in my price column in view - price values from all property tables (plot, house, flat). How can I display data from three property tables in one view. I can achieve it through multiple selects?

like image 668
mtmx Avatar asked Oct 21 '25 16:10

mtmx


1 Answers

The you need to use union, just like in plain select query:

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 

Here union all is fast but does not remove duplicates, if you don't want, them - use union instead.

like image 171
Andronicus Avatar answered Oct 23 '25 08:10

Andronicus