Re: weird structure - Mailing list pgsql-sql

From Yury Don
Subject Re: weird structure
Date
Msg-id 39A9E12C.CE30AB78@vpcit.ru
Whole thread Raw
In response to weird structure  (rdg@viafractal.com.br)
List pgsql-sql
Renato De Giovanni wrote:
> 
> > > Consider the following tables/fields:
> > > table "person": fields "p_id", "p_name".
> > > table "person_attribute": fields "a_id", "a_name".
> > > table "person_data": fields "d_person_id", "d_attribute_id",
> > > "d_value".
> > >
> > > Also consider that a person may not have data related to all possible
> > > attributes.
> > >
> > > Using this structure, how could I retrieve in one row with a single
> > > select statement all attributes from a person (showing null to
> > > attributes that were not registered to him)?
> > >
> > > Thanks for any suggestion,
> > > --
> > > Renato
> > > Sao Paulo - SP - Brasil
> > > rdg@viafractal.com.br
> >
> > I did similar things using the following technique:
> > in frontend I gather all attributes from person_attribute and then
> > generate a query like this:
> >
> > select *, (select distinct d_value from person_data where d_person_id =
> > person.p_id and
> > d_attribute_id = 'here first attribute id'), (select distinct d_value
> > from person_data where d_person_id = person.p_id and d_attribute_id =
> > 'here second attribute id'), ... from person
> > --
> > Sincerely yours,
> > Yury
> 
> Yury...
> That worked perfectly! Thank you very much!
> 
> Tell me, I've never seen this sql construction before, is it specific to
> postgres? Or should it also work on other databases?
> 
> And is there any relevant performance issue considering this kind of
> database schema and its peculiar sql commands?
> 
> Thanks again!
> --
> Renato
> Sao Paulo - SP - Brasil
> rdg@viafractal.com.br

This construction works in any database which support subselect in
target list in "select" statement, for example I used this in Interbase.
What about performance - it strongly depends on amount of attributes. In
order to maximize it you need to create indexes on all fields which
participate in "where" clause - p_id, d_person_id, d_attribute_id. And
performance .

-- 
Sincerely yours,
Yury


pgsql-sql by date:

Previous
From: "J. Fernando Moyano"
Date:
Subject: Complex query
Next
From: John McKown
Date:
Subject: Re: Select subset of rows