简体   繁体   中英

How to merge multiple columns using JSON in SQLite?

I have an SQLite database and there are multiple columns with the names like "column1" , "column2" , "column3" and so on, and I want to merge them into a single column named "column" , with its contents being the other columns' data in JSON format.

The resulting "column" would have a cell like this:

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

In order to achieve this, I think I should use a JSON extension for SQLite, but I couldn't figure out how to load it in DataGrip IDE or SQLiteDatabaseBrowser , and use it in SQL console.

How can I do it?

The documentation describes how to load an extension, which you should do for the json1 module.

Once the extension is loaded, you can use scalar function json_object() to generate a valid json object, like so:

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

If you want to actually create a new column in the table:

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
);

On Android, there are no SQLite extensions so json_object will not be available. In that case, use the contact operator instead.

instead of

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

use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM