【问题标题】:How to merge multiple columns using JSON in SQLite?如何在 SQLite 中使用 JSON 合并多个列?
【发布时间】:2020-04-11 11:54:51
【问题描述】:

我有一个 SQLite 数据库,并且有多个列的名称如 "column1""column2""column3" 和以此类推,我想将它们合并到一个名为 "column" 的列中,其内容是 JSON 格式的其他列的数据。

生成的“列”会有一个像这样的单元格:

{
    "column1": 1234,
    "column2": 4567,
    ...
}

为了实现这一点,我认为我应该为 SQLite 使用 JSON 扩展,但我不知道如何在 DataGrip IDESQLiteDatabaseBrowser 中加载它,并在 SQL 控制台中使用。

我该怎么做?

【问题讨论】:

    标签: sql json sqlite


    【解决方案1】:

    documentation 描述了如何加载扩展,您应该为 json1 模块执行此操作。

    加载扩展后,您可以使用scalar function json_object() 生成有效的 json 对象,如下所示:

    select
        t.*,
        json_object('column1', column1, 'column2', column2, 'column3', column3) as new_column
    from mytable t
    

    如果你想在表中实际创建一个新列:

    alter table mytable add new_column text;    -- json objects are stored as TEXT
    update mytable set new_column = json_object(
        'column1', column1, 'column2', column2, 'column3', column3
    );
    

    【讨论】:

      【解决方案2】:

      在 Android 上,没有 SQLite 扩展,因此 json_object 将不可用。在这种情况下,请改用联系运算符。

      而不是

      SELECT json_object('column1', column1, 'column2', column2) AS merged FROM table
      

      使用

      SELECT "{" || "column1"  || ":" || column1 || || "," || "column2"  || ":" || column2 ||  "}" AS merged FROM table
      

      【讨论】:

        猜你喜欢
        • 2019-04-30
        • 2016-04-17
        • 2018-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        相关资源
        最近更新 更多