V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
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
feihuxiongdi
V2EX  ›  MySQL

mysql 查询 json 中的字段是否为特定值

  •  1
     
  •   feihuxiongdi · Feb 1, 2019 · 6858 views
    This topic created in 2642 days ago, the information mentioned may be changed or developed.

    t1 表中有一字段 items 为 json 类型,存储的内容格式为:

    [
      {"id":1,"name":"a"},
      {"id":2,"name":"b"}
    ]
    

    我想查询是否包含 id 为 1 的表记录的数量,官方的 JSON_CONTAINS 函数好像是对于 json object 的,查询了一下对于 json array 并未查出正确结果。

    SELECT COUNT(*) FROM t1 WHERE JSON_CONTAINS(items, 1,'$.id')
    

    请问如何实现?

    4 replies    2019-02-26 09:42:30 +08:00
    cs8814336
        1
    cs8814336  
       Feb 18, 2019   ❤️ 2
    select `remarks` from `addrinfo`

    +------------------------------------------+
    | remarks |
    +------------------------------------------+
    | {"test": [{"id": "123"}, {"id": "243"}]} |
    | {"test": [{"id": "123"}, {"id": "243"}]} |
    | {"test": [{"id": "99"}, {"id": "243"}]} |
    | {"test": [{"id": "123"}, {"id": "243"}]} |


    select `remarks`->'$.test[*].id' ,json_contains(`remarks`->'$.test[*].id','"123"') from `addrinfo`;

    注意 json contains 里面 123 需要用双引号括住!!!
    feihuxiongdi
        2
    feihuxiongdi  
    OP
       Feb 19, 2019
    @cs8814336 数据库里存的是

    {"test": [{"id": 123}, {"id": 243}]}

    不是

    {"test": [{"id": __"__ 123 __"__ }, {"id": __"__ 243 __"__ }]}
    cs8814336
        3
    cs8814336  
       Feb 26, 2019
    @feihuxiongdi 什么意思.你那个是 json 结构吗 _"_123_"_ ?
    feihuxiongdi
        4
    feihuxiongdi  
    OP
       Feb 26, 2019
    @cs8814336 这是 markdown 加粗失败的结果😂。
    总之,按照你的语法查询再稍微修改一下就可以查询出来了。
    在此感谢一下。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   938 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 21:37 · PVG 05:37 · LAX 14:37 · JFK 17:37
    ♥ Do have faith in what you're doing.