V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
fuxkcsdn
V2EX  ›  MySQL

mysql json 查询如何匹配所有数组元素的属性?

  •  
  •   fuxkcsdn · 2018-12-28 16:51:43 +08:00 · 5592 次点击
    这是一个创建于 1917 天前的主题,其中的信息可能已经有所发展或是发生改变。

    mysql 版本 5.7.23

    期望的结果是查找 rsp.data.codes 数组中, object.code 值为 abc 的行

    是我的 json path 有误还是 mysql 不支持这样的查询呢?

    create table test(
      id int(1) unsigned auto_increment primary key,
      jdoc json
    )engine=InnoDB charset=utf8mb4;
    
    insert into test(jdoc) values
    ('{"req":["xyz"],"rsp":{"data":{"codes":[{"code":"abc"},{"code":"def"},{"code":"xyz"}]}}}'),
    ('{"req":["222"],"rsp":{"data":{"codes":[{"code":"ijk"},{"code":"opq"},{"code":"123"}]}}}');
    
    -- 记录为空
    select * from test where json_extract(jdoc, "$.rsp.data.codes[*].code") = "abc";
    
    -- 有记录
    select * from test where json_extract(jdoc, "$.rsp.data.codes[0].code") = "abc";
    
    fuxkcsdn
        1
    fuxkcsdn  
    OP
       2018-12-28 17:09:48 +08:00
    select * from test where JSON_CONTAINS(jdoc->"$.rsp.data.codes[*].code", JSON_ARRAY('abc'));

    or

    select * from test where JSON_CONTAINS(jdoc->"$.rsp.data.codes", JSON_OBJECT('code', 'abc'));

    v.a. https://stackoverflow.com/questions/38797627/query-a-json-column-with-an-array-of-object-in-mysql
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3030 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 15:01 · PVG 23:01 · LAX 08:01 · JFK 11:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.