这是我上一篇Find all matches for given team in PostgreSQL的后续问题。
这是我的数据结构。我有players
uuid | first_name | last_name
-----| -----------| ---------
... | hard | hitter
... | big | blocker
... | super | setter
两名队员在我的teams
表
uuid | player_1_uuid | player_2_uuid
-----|---------------|--------------
729..| f432f7bc-63...| e022ccb6-7...
d0f..| c9548a8e-b7...| a28441cb-2...
... | ... | ...
两支球队在我matches
牌桌中存储的比赛中相互比赛。
uuid | name | team_a_uuid | team_b_uuid
-----|------|-------------|------------
d7e..| foo | 5db46a15-...| 82732895-..
334..| bar | 75ab1a39-...| 9fcedf80-..
... | ... | ... | ...
在我之前的一个问题中,我询问了一个团队以及它所使用的所有匹配uuids。这是一个解决方案
select t.*,
(select array_agg(m.uuid)
from matches m
where t.uuid in (m.team_a_uuid, m.team_b_uuid)
) as match_uuids
from teams t;
现在我想更进一步:给我一个球员和它所参加的比赛uuids。这有点复杂,因为我们必须首先得到球队,然后是比赛。我想得到这样的东西
uuid | first_name | last_name | team_uuids | match_uuids
-----| -----------| ----------|---------------|---------------
... | hard | hitter | {'...', '...'}| {'...', '...'}
... | big | blocker | {'...', '...'}| {'...', '...'}
... | super | setter | {'...', '...'}| {'...', '...'}
有什么想法吗?
答案 0 :(得分:1)
我实际上无法运行查询(没有真正的表可供测试),但它应该是这样的:
memtable
我想,在SELECT
players.uuid,
players.first_name,
players.last_name,
array_agg(teams.uuid) AS team_uuids,
array_agg(matches.uuid) AS match_uuids
FROM
players
JOIN teams
ON (players.uuid = teams.player_1_uuid OR players.uuid = teams.player_2_uuid)
JOIN matches
ON (teams.uuid = matches.team_a_uuid OR teams.uuid = matches.team_b_uuid)
GROUP BY
players.uuid,
players.first_name,
players.last_name;
子句中GROUP BY
列就足够了,如果它是主键 - 您可以尝试删除players.uuid
和players.first_name
列。