Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/96.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL:行到列的变体_Postgresql - Fatal编程技术网

PostgreSQL:行到列的变体

PostgreSQL:行到列的变体,postgresql,Postgresql,postgresql V9.3 最好用一个例子来解释: 所以我有两张桌子: 图书目录: book_id name 1 Aragorn 2 Harry Potter 3 The Great Gatsby 4 Book name, with a comma 用户ID到图书ID表: user_id book_id 31 1 31 2 32 3 34 1 34

postgresql V9.3

最好用一个例子来解释:

所以我有两张桌子:

图书目录:

book_id   name
1         Aragorn
2         Harry Potter
3         The Great Gatsby
4         Book name, with a comma
用户ID到图书ID表:

user_id    book_id
31         1
31         2
32         3
34         1
34         4
我想向每个用户展示他/她的书籍,比如:

user_id   book_names
31        Aragorn,Harry Potter
32        The Great Gatsby
34        Aragorn,Book name, with a comma
基本上,每个用户的书籍都用逗号隔开


如何有效地实现这一点?

如果您使用的是Postgres 8.4版或更高版本,那么您可以使用array_agg。一个选项是按用户id在用户图书表上聚合,然后使用array\u agg为每个用户生成图书的CSV列表

SELECT t1.user_id,
       array_to_string(array_agg(t2.name), ',') AS book_names
FROM user_books t1
INNER JOIN books t2
    ON t1.book_id = t2.book_id
GROUP BY t1.user_id
在Postgres 9.0及以上版本中,您可以使用以下内容将书名聚合到CSV列表中:

string_agg(t2.name, ',' order by t2.name)
所以string_aggt2.name,,“按t2.name而不是数组排序,”,我给了8.4+和9.x的选项。我给你的9.x选项还按字母顺序升序排列CSV列表中的书籍,这似乎是你想要的。如果您使用的是9.0,那么选择string_agg选项。