2

MySQL5.7 的 JSON 数组,数组元素是 Object,想查询该数组 Object 的某几个字段同时成...

 2 years ago
source link: https://www.v2ex.com/t/808090
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

MySQL5.7 的 JSON 数组,数组元素是 Object,想查询该数组 Object 的某几个字段同时成立!求各位帮帮孩子,查一下午不知道怎么解决

  v2exblog · 1 天前 · 695 次点击

因为业务从 mongodb 迁移到 mysql5.7,有一些 mongo 特殊的查询就需要修改。
想做到尽可能少改代码,并且需要支持 mongodb 的 $eleMatch 查询 (感觉难得不行)

CREATE TABLE `Student` (
  `id` bigint AUTO_INCREMENT PRIMARY KEY, 
  `name` varchar(64),
  `gender` varchar(32),
  `data` json DEFAULT NULL
) 

上面是简化后的表结构,实际上字段很丰富。主要是 data 字段是 JSON 格式,
大概长这样:

[
    {"date":"2021-01-01", "is_active": true, "tags":["A", "B", "C", "D"]},
    {"date":"2021-06-01", "is_active": false, "tags":["C", "D"]},
]

想查询如下:

  1. 名字为 “小明”,性别为“女”,

  2. data.date 在 2020-08-01 到 2020-05-01 之间,

  3. 并且 is_active 为 true,

  4. tags 中含有"C" 和 "D"的 -- 这个可以通过读到内存后过滤

查了一下午,试用了各种 json_extract 类似的函数,都没办法做到 [数组内的 Object 同时满足多个条件]

网上还有说用 mysql8.0 自带的 json_table 函数,,目前还没有测试,不知道能不能见索引。

求有经验的老哥说一下,跪谢跪谢跪谢跪谢跪谢跪谢跪谢


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK