简体   繁体   English

从 json 中提取唯一值的 SQLite 查询

[英]SQLite query to extract unique values from json

For use in React Native,为了在 React Native 中使用,

Suppose I have a SQLite database table contains col1 primary, col2.假设我有一个 SQLite 数据库表,其中包含 col1 primary、col2。

Where col1 contains a serial number and col2 contains a JSON like其中 col1 包含序列号, col2 包含类似的 JSON

col1   :    col2
  1    :   {"id":"id1", "value":"value1"}, 
  2    :   {"id":"id2", "value":"value2, value3"}, 
  3    :   {"id":"id3", "value":"value4, value5"}

and I just want to extract those unique value using SQLite query, output I expect is : ["value1","value2","value3","value4","value"]我只想使用 SQLite 查询提取那些唯一值,我期望的输出是: ["value1","value2","value3","value4","value"]

You can do it with json_extract() :你可以用json_extract()做到这json_extract()

select group_concat(json_extract(col2, '$.value'), ', ') result
from tablename

Result:结果:

> result                                
> -------------------------------------
> value1, value2, value3, value4, value5

Or if you want the result formatted as a json array use json_group_array() :或者,如果您希望将结果格式化为 json 数组,请使用json_group_array()

select replace(json_group_array(json_extract(col2, '$.value')), ', ', '","') result
from tablename

Result:结果:

> | result                                         |
> | :--------------------------------------------- |
> | ["value1","value2","value3","value4","value5"] |

If you can' use the JSON1 Extension then you can do it with string functions:如果您不能使用JSON1 扩展,那么您可以使用字符串函数来实现:

select group_concat(substr(
         col2, 
         instr(col2, '"value":"') + length('"value":"'), 
         length(col2) - (instr(col2, '"value":"') + length('"value":"') + 1)
       ), ', ') result
from tablename

Result:结果:

> result                                
> -------------------------------------
> value1, value2, value3, value4, value5

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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