Having not a SQLite background, I'm struggling building a "simple" SQLite query.
Considering the simplified schema below:

** Table: EVENTS **
id   content
1    abc
2    xyz

** Table: TIMESLOTS **
id   start     end
1    05-2022   06-2022
1    10-2022   12-2022
2   .......  .......

我想要在下面这样的基础上构建对象:

{
  id: 1,
  content: abc,
  timeslots:
    [
     {start: 05-2022, end: 06-2022},
     {start: 10-2022, end: 12-2022},
     ...
    ]
},
...

我能够在2个查询中完成它,然后以编程方式构建对象(很容易!)

SELECT * FROM events WHERE id = 1
SELECT * FROM timeslots WHERE id = 1

But I'd like to make it in 1 to leverage DB power, not JS.
Is there a simple way to do it? JOIN doesn't seem to allow me building this kind of object.

推荐答案

您可以联接这些表,按id聚合并使用SQLite's JSON functions来构建json对象:

SELECT json_object(
         'id', e.id,
         'content', e.content,
         'timeslots', json_group_array(
                        json_object(
                          'start', t.start,
                          'end', t.end
                        )
                      )
       ) col
FROM events e INNER JOIN timeslots t
ON t.id = e.id
-- WHERE e.id = ?
GROUP BY e.id;

See the demo.

Sql相关问答推荐

从列的不同值创建列

Postgres JSONB对象筛选

retrofit AWS Athena中的JSON

如何在Presto中将多个列合并到一个数组中

Oracle SQL根据列中的条件 Select 最大记录数

连接三个表的正确方式是什么?在这三个表中,可以显示在一个表上的行将在其他表中显示结果

从字符串中删除";1、";和";2,";,而不删除";11、";和";12、";

NULL-生成的列中连接的字符串的输入

按日期时间(不包括秒)连接表

如何用客户名称计算sum(dr)和sum(cr)

IF NOT EXISTS子查询的性能瓶颈

将 jsonb 数组中的对象取消嵌套到单独的行中

从每月生成的系列中生成每日汇率

如何使用 Google BigQuery 中的条件根据特定列值连接列的 N 行?

JSON对象查询SQL服务器

如何获取每个组中最近的n条记录并将它们聚合成数组

如何通过CROSS APPLY获取多级嵌套JSON属性的值?

连续期间的缺口

SQL Group By 然后映射出是否存在值

SQL中所有先前日期的累计总和