0

我对我在 PostgreSQL 中进行的查询有一个未解决的疑问。

我有这两张桌子

播放器

playerID      title
1             Rondo
2             Allen
3             Pierce
4             Garnett
5             Perkins<

播放

playerID      TeamID
   1             1
   1             2
   1             3
   2             1
   2             3
   3             1
   3             3

这就是我的查询

SELECT DISTINCT concat(N.playerID, ':', N.title), TID 
FROM player N
INNER JOIN (
 SELECT DISTINCT P.playerID  as PID,  teamID as TID
 FROM plays P
 ) AS derivedTable 
ON N.playerID = PID
ORDER BY concat

查询的结果是:

"1:Rondo"  |  1 
"1:Rondo"  |  2
"1:Rondo"  |  3
"2:Allen"  |  1
"2:Allen"  |  3
"3:Pierce" |  1
"3:Pierce" |  3

但我想要这样的东西

"1:Rondo"  |  1, 2, 3
"2:Allen"  |  1, 3
"3:Pierce" |  1, 3

我可以使用 array_agg,但我真的不知道如何

4

3 回答 3

0

对于MySQL

试试这个:

SELECT CONCAT(N.playerID, ':', N.title) playerTitle, 
       GROUP_CONCAT(P.TID SEPARATOR ', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = PID 
GROUP BY N.playerID
ORDER BY playerTitle
于 2014-12-16T14:03:45.327 回答
0

采用string_agg()

SELECT concat(N.playerID, ':', N.title), 
       string_agg(p.TeamID::text, ',') as teamid_list
FROM player N
  JOIN plays p ON n.playerID = p.playerID
GROUP BY n.playerID, n.title
ORDER BY 1;

您的派生表不是必需的(并且不同的更是如此)

于 2014-12-16T14:06:22.627 回答
0

在 Postgres 中应该是:

SELECT concat(N.playerID, ':', N.title) title, string_agg(P.TID,', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = P.PID 
GROUP BY 1
ORDER BY 1
于 2014-12-16T14:08:31.437 回答