PostgreSQL查找给定玩家的所有匹配项

PostgreSQL查找给定玩家的所有匹配项,sql,postgresql,Sql,Postgresql,这是我最后一个问题的后续问题 这是我的数据结构。我有球员 在我的团队表中,两名球员组成一个团队 两支球队在我的比赛表中的一场比赛中相互对抗 在我的上一个问题中,我问了关于组建一支球队以及它参加过的所有比赛UUID的问题。这里有一个解决方案 select t.*, (select array_agg(m.uuid) from matches m where t.uuid in (m.team_a_uuid, m.team_b_uuid) ) as match_uui

这是我最后一个问题的后续问题

这是我的数据结构。我有球员

在我的团队表中,两名球员组成一个团队

两支球队在我的比赛表中的一场比赛中相互对抗

在我的上一个问题中,我问了关于组建一支球队以及它参加过的所有比赛UUID的问题。这里有一个解决方案

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;
现在我想更进一步:给我一个球员和他参加过的比赛。这有点复杂,因为我们必须先得到球队,然后是比赛。我想要这样的东西

uuid | first_name | last_name | team_uuids    | match_uuids
-----| -----------| ----------|---------------|---------------
...  | hard       | hitter    | {'...', '...'}| {'...', '...'}
...  | big        | blocker   | {'...', '...'}| {'...', '...'}
...  | super      | setter    | {'...', '...'}| {'...', '...'}

有什么想法吗?

我实际上无法运行查询,没有真正的表要测试,但它应该是这样的:

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和players.last_name列。

它可以工作:谢谢!我在团队中得到了重复的UUID。array\u aggdistentic teams.uuid作为team\u uuid是删除重复项的正确方法吗?@zemirco,是的,array\u aggdistentic teams.uuid将删除重复项并按此方法对uuid进行排序。我很高兴能帮上忙。@zemirco。我期待着你的下一个问题,你会问如何在有限的时间内得到这个回报。我对SQL非常陌生。这些查询的性能有那么差吗?或者你的评论是什么意思?我如何改进它们?
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;
uuid | first_name | last_name | team_uuids    | match_uuids
-----| -----------| ----------|---------------|---------------
...  | hard       | hitter    | {'...', '...'}| {'...', '...'}
...  | big        | blocker   | {'...', '...'}| {'...', '...'}
...  | super      | setter    | {'...', '...'}| {'...', '...'}
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;