【问题标题】:PostgreSQL select multiple columns of a table that is connected via a many-to-many pivotPostgreSQL选择通过多对多枢轴连接的表的多个列
【发布时间】:2019-07-11 16:23:08
【问题描述】:

我有这个问题:

SELECT
    a.account_uuid,
    a.account_no,
    a.account_group_uuid,
    a.account_scope_uuid,
    a.created_at,
    a.deleted_at,
    s.service_uuid,
    s.status,
    st.service_type,
(
    SELECT
            c.company
    FROM companies c
    WHERE a.company_owner_uuid = c.company_uuid   
)
FROM
    accounts a 
LEFT JOIN
    services s 
ON a.account_uuid = s.account_uuid 
LEFT JOIN
    service_types st 
ON s.service_type_uuid = st.service_type_uuid
WHERE
    a.deleted_at IS NULL
ORDER BY
    a.account_no

我需要通过具有 account_uuid 和 person_uuid 的数据透视表 accounts_contactspeople 表中加入和选择多个列。 accounts_contacts 表上还有 is_primaryis_active 列,一次只有一个主列,因此最终结果将是一个名字和姓氏。这是查询的想法:

SELECT
    p.first_name, p.last_name 
FROM
    people p 
INNER JOIN
    accounts_contacts ac 
ON ac.account_uuid = a.account_uuid 
AND ac.person_uuid = p.person_uuid 
WHERE
    ac.is_primary = true 
AND ac.is_active = true

但不确定如何将其放入上述查询中。子查询只允许其中一列。

【问题讨论】:

    标签: sql postgresql join many-to-many pivot-table


    【解决方案1】:

    account_contacts 是一个“关联”或“联结”表。它不是数据透视表。

    基本思路应该是joins:

    SELECT . . . ,
           p.first_name, p.last_name 
    FROM accounts a LEFT JOIN
         services s 
         ON a.account_uuid = s.account_uuid LEFT JOIN
         service_types st 
         ON s.service_type_uuid = st.service_type_uuid LEFT JOIN
         accounts_contacts ac 
         ON ac.account_uuid = a.account_uuid LEFT JOIN
         people p
         ON ac.person_uuid = p.person_uuid AND
            ac.is_primary = true AND
            ac.is_active = true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多