简体   繁体   English

将多行的列列为行(postgres SQL)

[英]List columns of multiple row as rows (postgres SQL)

I tried to think of a sql query to get results consisting of multiple columns from multiple records, which the table is like: 我试图想到一个sql查询,以从多个记录中获取包含多个列的结果,该表类似于:

key_1     key_2
--------------------
1         2
1         3
1         4
5         6

Both key_1 and key_2 are primary keys from another table. key_1和key_2都是来自另一个表的主键。 And the result I want to obtain is getting every key that are related to the key '1', which is: 我想要获得的结果是获取与键“ 1”相关的每个键,即:

key
--------
1
2
3
4

I tried the following query: 我尝试了以下查询:

SELECT key_1 as key FROM tbl_keys_link WHERE key_1 IN (1)
UNION
SELEVY key_2 as key FROM tbl_keys_link WHERE key_2 IN (1)

But I examined it using pgadmin's 'Explain' function, seems the process time of this query is not very optimal. 但是我使用pgadmin的'Explain'函数检查了它,看来这个查询的处理时间不是很理想。 Is there any other ways to construct a query to achieve this with a better performance? 还有其他方法可以构造查询以实现更好的性能吗? Thanks! 谢谢!

You can try phrasing the query like this: 您可以尝试对查询进行这样的表述:

select a.key
from anothertable a
where exists (select 1 from tbl_keys_link p pairs.key_1 = a.key and pairs.key_2 = 1) or
      exists (select 1 from tbl_keys_link p pairs.key_2 = a.key and pairs.key_1 = 1);

For performance, you will want two indexes: tbl_keys_link(key_1, key_2) and tbl_keys_link(key_2, key1) . 为了提高性能,您将需要两个索引: tbl_keys_link(key_1, key_2)tbl_keys_link(key_2, key1)

This eliminates the duplicate elimination step (needed for the distinct). 这消除了重复消除步骤(非重复步骤所需)。 Also, the query should just scan the other table and do one or two index lookups to identify the matching keys. 同样,查询应只扫描另一个表并执行一个或两个索引查找以识别匹配的键。

You can try this: 您可以尝试以下方法:

with keys as (
  select key_1, key_2
  from tbl_keys_link 
  where key_1 = 1 
     or key_2 = 1
)
SELECT distinct unnest(array[key_1, key_2]) 
from keys
order by 1;

But I have no idea if that is more efficient. 但是我不知道这样是否更有效。 At least it only needs to scan the table once. 至少它只需要扫描表一次。 If you have an index on each column, Postgres might be able to use those indexes for searching the "relevant" rows. 如果您在每列上都有一个索引,则Postgres也许可以使用这些索引来搜索“相关”行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM