Question about database design and views
Say i have a database of real-estate properties (apartments, houses, industrial spaces, offices) and each have a set of common attributes ( the ones common to all constructions like address, price, description text, coordinates, available surface inside building, resistance-frame material type (steel, wood, clay :D etc..) etc.). Should i :
1) create tables apartments, houses, offices etc. and, when i do a select-query that involves all constructions, use a view (say all_constr)that selects from all of the tables based on the common attributes and then refine the result based on various criteria (eg.resistance-frame made with wood or made with (concrete-steel OR clay) etc.)
I'm not exaclty sure how a view works under the hood but i think that if i do something like
SELECT * FROM al开发者_如何学运维l_constr AS a --all_constr is the view
WHERE a.price <50000 AND a.surface >100 ;
everytime i run the above query the specific-building tables are iterated once to create the virtual table and the again to do the filtering. This does not seem very efficient. On the other hand, if the virtual table AKA view is stored as a real table then it's pretty much the same thing as case 2) + in case i want to see building-specific details i'm out of luck because there is no unique identifier across houses, aps, etc. One solution,i think, would be to create the view like this :
CREATE VIEW all_constr AS
SELECT x.common_att1, x.common_att2, x.tableoid, x.id
FROM aps AS x
UNION ALL
SELECT x.common_att1, x.common_att2, x.tableoid, x.id
FROM houses AS x
UNION ALL
SELECT x.common_att1, x.common_att2, x.tableoid, x.id
FROM ind_spaces AS x
2) create another table (say constr) and link aps,houses like this :
http://imageshack.us/photo/my-images/31/unledkwx.png/ This has the advantage of not needing to use tableoids
So which solution would you recommend seeing as how i hear and read many times that using views is good practice?
LE: If possible i would like to avoid using inheritance as its too postgres specific ( i dont mind very much tho as long as it is an optimal solution )
in PostgreSQL, views are a shorthand for rules.
When the query planner encounters a rule/view, it substitutes the query fragment from the rule into the current query, and continues optimizing the query.
It's the same as if you had entered the query from the view directly; postgresql will optimize the query as if there were no view at all, and do the most efficient thing it can. There is no performance penalty for using a view.
Combine all the common stuff into one table and add a 'type' (reserved word ...) column to this table. Make optional attributes nullable, or put them into one or more separate tables.
精彩评论