Re: Most efficient way of querying M 'related' tables where N out of M may contain the key

Поиск
Список
Период
Сортировка
От Stephane Bailliez
Тема Re: Most efficient way of querying M 'related' tables where N out of M may contain the key
Дата
Msg-id CACDwtRcFd_mpo3nX6L5_k1+axWZyCOgLp0t6uYfyzTZ2dWmTwg@mail.gmail.com
обсуждение исходный текст
Ответ на Re: Most efficient way of querying M 'related' tables where N out of M may contain the key  ("David G. Johnston" <david.g.johnston@gmail.com>)
Ответы Re: Most efficient way of querying M 'related' tables where N out of M may contain the key  ("David G. Johnston" <david.g.johnston@gmail.com>)
Список pgsql-performance

On Thu, Aug 20, 2015 at 8:19 PM, David G. Johnston <david.g.johnston@gmail.com> wrote:

​SELECT [...]
FROM (SELECT reference_id, [...] FROM table_where_referenced_id_is_a_pk WHERE reference_id EXISTS/IN/JOIN)​
 
​src
​LEFT JOIN type1 USING (reference_id)
LEFT JOIN type2 USING (reference_id)
[...]


there are no tables where reference_id is a pk, I could create one or do : select reference_id from ( values (..), (...), (...) .... )

the tricky part with the join (and where I was not clear about it in my original description) is that a reference_id  can match in multiple tables (eg. it can be a fk in type1 and type2), so it then becomes a bit harder to collect all the common attributes and 'types' when doing joins like this.

For example let's assume there is a group_id to be be retrieved among all tables as a common attribute:

if reference_id was existing only in one table, I could do coalesce(type1.group_id, ... type5.group_id) as group_id in the main select
however that would not work in this case.

I could work around the common attributes however. 

But for retrieving the types, what I really need to have as a return of this query is data that allows me to partition the reference_id for each type like:

type1 -> ref1, ref2, ref5
type2 -> ref1, ref3
type3 -> ref4, ref3

 I guess I could try to return an array and fill it with case/when for each table eg. something like
ARRAY( CASE WHEN type1.id IS NOT NULL THEN 'type1' END, ... CASE WHEN type1.id IS NOT NULL THEN 'type5' END)

and then collect all the non-null values in the code.

 

Or consider whether PostgreSQL Inheritance would work - though basically its a friendly API over the "UNION ALL" query you proposed.


The problem with postgresql inheritance is that it would not play well with the orm and substantially complicates implementation.


Thanks for the all the ideas,  that helps me a lot to brainstorm more.


В списке pgsql-performance по дате отправления:

Предыдущее
От: "David G. Johnston"
Дата:
Сообщение: Re: Most efficient way of querying M 'related' tables where N out of M may contain the key
Следующее
От: "David G. Johnston"
Дата:
Сообщение: Re: Most efficient way of querying M 'related' tables where N out of M may contain the key