tomatokiller
V2EX  ›  程序员

在 Sqlite 中,怎么查询树形结构的 JSON 数据

By tomatokiller at 2022 年 3 月 2 日 · 4327 次点击

在我的 sqlite 数据库表中,有一个树形结构的 JSON 数据字段,它大概长这样,现在我想通过 title 关键字做查询筛选,请问有什么好的方法吗?

[
  {
    id: '100',
    title: 'Frontend',
    children: [
      {
        id: '110',
        title: 'React',
        children: [
          {
            id: '111',
            title: 'React Hooks',
          },
          {
            id: '112',
            title: 'React Router',
          },
        ],
      },
      {
        id: '120',
        title: 'Vue',
        children: [
          {
            id: '121',
            title: 'Vue Router',
          },
          {
            id: '122',
            title: 'Vuex',
          },
        ],
      },
    ],
  },
  {
    id: '200',
    title: 'Backend',
    children: [
      {
        id: '210',
        title: 'Java',
      },
      {
        id: '220',
        title: 'Rust',
      },
    ],
  },
]
11 条回复  •  2022-03-03 16:04:22 +08:00
Akiya
   1
Akiya  
   2022 年 3 月 2 日   ❤️ 1
这时候你就需要 mongodb 或者其他的 nosql 数据库了,对于这种最合适的肯定是图数据库。当然你要存在 sqlite 也不是没有办法,无非就是加一个 ID 和 FatherID 字段,记录每个节点的父亲节点,只是你要还原出这个 json 就需要 BFS 遍历一下
corningsun
   2
corningsun  
   2022 年 3 月 2 日   ❤️ 1
大部分关系型数据库都能支持 JSON 查询的,不用无脑上 nosql 。

sqlite 也是支持 JSON 的,查询函数可以参考: https://www.sqlite.org/json1.html
swcat
   3
swcat  
   2022 年 3 月 2 日   ❤️ 1
sqlite 用 json_each
mysql 用 json_table

sqlite:
select * from t, json_each(content) where json_extract(json_each.value, '$.title') = 'Backend';
tomatokiller
   5
tomatokiller  
OP
   2022 年 3 月 2 日
@Akiya 同意你的观点,对于 JSON 数据的存储,还是 nosql 数据库方便,不过我们的需求是需要客户端离线存储,不得已选了 sqlite ,你提供的 ID 和 FatherID 的方案是一个好方法,感谢!
tomatokiller
   6
tomatokiller  
OP
   2022 年 3 月 2 日
@corningsun 棒哇,json_each 和 json_tree 看上去可以满足我的需求,感谢~
tomatokiller
   7
tomatokiller  
OP
   2022 年 3 月 2 日
@swcat 👍,我试试,字段结构是一个树形数组,如果 json_each 不行,可能需要 json_tree 配合使用
codehz
   8
codehz  
   2022 年 3 月 2 日 via Android
最近 SQLite 增加了->和->>运算符,大概不需要写一长串 extract 了(虽然还是需要 json_each 来分离数组
papaer
   9
papaer  
   2022 年 3 月 3 日
请问你们用为什么用 Sqlite ?
papaer
   10
papaer  
   2022 年 3 月 3 日
或者说使用 sqlite 的场景是什么
tomatokiller
   11
tomatokiller  
OP
   2022 年 3 月 3 日
@papaer 需要跨平台的数据离线存储
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
© 2026 V2EX · 44ms · 3.9.8.5