简体   繁体   English

在查询 postgres 中访问数组元素

[英]Accessing array elements in query postgres

I'm currently building a query to retrieve some data from my db, I need to access the documents stored in an array, this is how the table crm_company looks:我目前正在构建一个查询以从我的数据库中检索一些数据,我需要访问存储在数组中的文档,这就是表crm_company的样子:

+ company_id +         documents_avaiable       + 
-     1      - [71788176,98705180,21468287,...] -   
-     2      - [11218494,12825726,10353038,...] -                                 

I have another table for users by document crm_user which looks like this:我通过文档crm_user为用户创建了另一个表,如下所示:

+ user_document +     email     +
-   71788176    - abc@email.com -  
-   98705180    - def@email.com - 
-   11218494    - hef@email.com - 

What I want as a final result is:我想要的最终结果是:

+ user_document +     email     + company +
-   71788176    - abc@email.com -    1    -
-   98705180    - def@email.com -    1    -

I just have tried somehing like the following:我刚刚尝试过如下操作:

select documents_avaiable[0] from crm_company where crm_company.id = 1

But I'm still unable to retrieve the documents from array.但我仍然无法从数组中检索文档。

Thanks in advance for any hint or help.在此先感谢您的任何提示或帮助。

If it's too late to follow the advice in the comment of Laurenz Albe then do this:如果现在听从 Laurenz Albe 评论中的建议为时已晚,请执行以下操作:

  1. Use a query (or create a view) to have the list of company documents normalized使用查询(或创建视图)对公司文档列表进行规范化

    create view company_documents as select t.company_id, l.document_id from crm_company t cross join lateral ( select unnest(t.documents_avaiable) as document_id ) l;
  2. Access documents' details in other tables by document_id using join使用join通过document_id访问其他表中的文档详细信息

    select cd.document_id user_document, cd.company_id company, d.email from company_documents cd join crm_user d on cd.document_id = d.user_document;

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

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