SQL 多对多子查询
SQL many to many subquery
这是一个 SQLFiddle,它显示了我当前的查询:
我更愿意为每个联系人+位置关联显示一行,并将所有角色分组。因此,我会得到 2 个结果,而不是 5 个结果 - 每个唯一的位置+联系人组合都有一个结果,并且该联系人的所有角色组合成一个数组或其他东西。
不确定原始 SQL 是否可行。
基于模式的期望结果:
location 1 ryan accountant, admin
location 2 steve admin, manager, developer
只应显示有联系人的地点。
使用array_agg
.
SELECT
locations."name",
contacts.name,
array_agg(roles."name") AS "Roles"
FROM locations INNER JOIN contacts ON locations."id" = contacts.location_id
INNER JOIN "public".memberships ON "public".memberships.contact_id = contacts."id"
INNER JOIN roles ON "public".memberships.role_id = roles."id"
group by locations."name", contacts.name
SELECT DISTINCT
locations."id",
locations."name",
contacts.name
FROM locations
JOIN contacts ON locations."id" = contacts.location_id
这是一个 SQLFiddle,它显示了我当前的查询:
我更愿意为每个联系人+位置关联显示一行,并将所有角色分组。因此,我会得到 2 个结果,而不是 5 个结果 - 每个唯一的位置+联系人组合都有一个结果,并且该联系人的所有角色组合成一个数组或其他东西。
不确定原始 SQL 是否可行。
基于模式的期望结果:
location 1 ryan accountant, admin
location 2 steve admin, manager, developer
只应显示有联系人的地点。
使用array_agg
.
SELECT
locations."name",
contacts.name,
array_agg(roles."name") AS "Roles"
FROM locations INNER JOIN contacts ON locations."id" = contacts.location_id
INNER JOIN "public".memberships ON "public".memberships.contact_id = contacts."id"
INNER JOIN roles ON "public".memberships.role_id = roles."id"
group by locations."name", contacts.name
SELECT DISTINCT
locations."id",
locations."name",
contacts.name
FROM locations
JOIN contacts ON locations."id" = contacts.location_id