sql - PostgreSQL : Alternative to joining the same table multiple times

标签 sql postgresql join database-table

如果我有两个表entryentry_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/

相关文章:

mysql - 在 MySQL 多对多表中获取唯一成员资格

python - 如何将图像插入 sqlite3 数据库?

sql按列中的特定值排序,而不是按字母顺序排列同一列的其余部分

mysql - 有没有办法将一行作为参数传递给 MySQL 函数?

python - 在 Ubuntu 上安装 psycopg2

sql - PostgreSql 中的简单聚合查询非常慢,有什么改进方法吗?

sql-server - SQL Server 2012 查询日期

mysql - 查找其他人查看的前 N ​​个产品(在 MySQL 中)

sql - 如何使用 Postgres 聚合 JSON 对象数组?

list - 在CMake中加入列表的最佳/最短方法