返回多列或 JSON 对象的子查询

dot*_*nor 0 postgresql

有没有办法让我从子查询返回多个列,或者至少返回一个作为我需要的所有列的 JSON 对象的列?

这是一个有效的查询:

select r.*,
       (select status
        from builds
        where repo = r.id
          and branch = 'master'
        order by id desc
        limit 1)
from repos r
where id = any($1)
Run Code Online (Sandbox Code Playgroud)

在哪里$1id 数组在

但我想返回的不仅仅是表中的状态列builds

select r.*,
       (select status, start_time, end_time
        from builds
        where repo = r.id
          and branch = 'master'
        order by id desc
        limit 1)
from repos r
where id = any($1)
Run Code Online (Sandbox Code Playgroud)

环顾四周后,似乎这row_to_json应该对我有用。但是,我不确定在这种情况下它应该如何工作:

select r.*,
       row_to_json(select status,
                   start_time, end_time
                   from builds
                   where repo = r.id
                     and branch = 'master'
                   order by id desc
                   limit 1) as build
from repos r
where id = any($1)
Run Code Online (Sandbox Code Playgroud)

我正进入(状态

syntax error at or near "select"
Run Code Online (Sandbox Code Playgroud)

Lau*_*lbe 7

不要让自己的生活变得困难,使用横向连接:

SELECT r.*, 
       b.status, b.start_time, b.end_time
FROM repos AS r
   LEFT JOIN LATERAL
      (SELECT status, start_time, end_time
       FROM builds
       WHERE repo = r.id
         AND branch = 'master'
       ORDER BY id DESC
       LIMIT 1
      ) AS b ON TRUE
WHERE id = ANY($1);
Run Code Online (Sandbox Code Playgroud)