如果我有两个表entry 和entry_metadata,其中entry_metadata 作为entry_id 引用的条目的描述表和一个变量。
如果我有这个:
进入
id | name |
-------------
1 | entry1 |
2 | entry2 |
3 | entry3 |
条目元数据
id | entry_id | variable | value
1 | 1 | width | 10
2 | 1 | height | 5
3 | 2 | width | 8
4 | 2 | height | 7
5 | ... | .... | ..
我正在整理 table :
id | name | width | height| ... | ...
-----------------------------------------
1 | entry1 | 10 | 5 |
2 | entry2 | 8 | 7 |
3 | entry3 | .. | .. |
通过 sql :
select e.name, em.width, emr.height
from
public.entry e
left join
public.entry_metadata em
on
em.entry_id = e.id and em.variable = 'width'
left join
public.entry_metadata emr
on
emr.entry_id = e.id and emr.variable = 'height'
上面的查询有效。但是当我添加更多变量以从条目元数据中获取值(entry_metadata 表包含大量变量)时。查询变得非常非常慢。我做的每一次加入都会大大减慢执行速度。有办法解决这个问题吗?
最佳答案
您也可以使用条件聚合来做到这一点:
select id, name,
max(case when variable = 'width' then value end) as width,
max(case when variable = 'height' then value end) as height
from public.entry_metadata em
group by id, name;
添加额外的列只是添加更多的聚合函数。
关于sql - PostgreSQL : Alternative to joining the same table multiple times,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30496311/