SQL数组agg和联接

Wil*_*alk 5 sql postgresql join knex.js array-agg

在我的Postgres数据库中,我有3个表。一个用于users一个用于comments和一个映射两种user_comment_map。表格的外观如下:

users
| id | name | age |
|----|------|-----|
| 1  | user | 20  |


comments
| id | mood  | subject | content         | created_at               |
|----|-------|---------|-----------------|--------------------------|
| 1  | happy | funny   | here is content | Tue Sep 27 2016 13:44:19 |
| 2  | silly | cool    | more content    | Tue Sep 27 2016 14:44:19 |

user_comment_map
| id | user_id | comment_id |
|----|---------|------------|
| 1  |        1|           1|
| 2  |        1|           2|
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个导致以下对象的SQL查询:

[{
  id: 1,
  name: "user",
  age: 20,
  comments: [
    {
      id: 1,
      mood: "happy",
      subject: "silly",
      content: "here is content",
      created_at: "Tue Sep 27 2016 13:44:19"
    }, 
    {
      id: 2,
      mood: "silly",
      subject: "cool",
      content: "more content",
      created_at: "Tue Sep 27 2016 14:44:19"
    },
  },
  {...}
]
Run Code Online (Sandbox Code Playgroud)

我尝试使用joinsarray_agg但无法获得该格式的数据。任何帮助将非常感激。注意:我也使用knex来构建查询,但是我不认为knex可以在不诉诸于此的情况下处理类似的事情knex.raw

red*_*neb 6

应该这样做:

SELECT
    json_build_object(
        'id',id,
        'name',name,
        'comments',(
            SELECT json_agg(json_build_object(
                'id', comments.id,
                'mood', comments.mood,
                'subject', comments.subject,
                'content', comments.content,
                'created_at', comments.created_at
            ))
            FROM user_comment_map JOIN comments ON comment_id=comments.id
            WHERE user_id=users.id
        )
    )
FROM users
WHERE id=1;
Run Code Online (Sandbox Code Playgroud)