V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
xjmroot
V2EX  ›  问与答

[Mysql] Json 数据 in 查询 问题?该怎么写查询呢, v2 大神们帮忙瞅瞅撒

  •  1
     
  •   xjmroot · Oct 11, 2017 · 3881 views
    This topic created in 3130 days ago, the information mentioned may be changed or developed.

    [问题] 如何查询出 json_data 字段 里面所有项的任意一项,包含 1 的数据。v2 大神们帮忙瞅瞅撒

    [备注] 每个 json_data 字段内都只有 3 项( country、province、city ),格式统一为{"country":[],"province":[],"city":[]}

    • 数据表结构如下
    --创建表
    CREATE TABLE json_test (
    	id INT (11) AUTO_INCREMENT PRIMARY KEY,
    	json_data JSON #这是要查询的字段
    ) ENGINE INNODB ;
    --插入数据,json 内包含 3 项 country、province、city、district
    INSERT INTO `json_test` (json_data) VALUES ('{
        "country": [11,22,1],
        "province": [11,22,33],
        "city": [11,22]
    }');
    INSERT INTO `json_test` (json_data) VALUES ('{
        "country": [1,22,33],
        "province": [11,1,33],
        "city": [11,1]
    }');
    
    • 查询语句该怎么写噢,硬是没弄出来
    1 replies    2017-10-12 10:20:27 +08:00
    xjmroot
        1
    xjmroot  
    OP
       Oct 12, 2017
    解决了,使用 json_contains+JSON_EXTRACT 就可以
    这样查询
    SELECT * FROM `json_test` WHERE json_contains(JSON_EXTRACT(json_data,'$.city'), '[1]');
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1095 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 18:04 · PVG 02:04 · LAX 11:04 · JFK 14:04
    ♥ Do have faith in what you're doing.