› 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
sunmoon1983
V2EX  ›  MySQL

大老们,为什么我查不出来结果呢?

  •  
  •   sunmoon1983 · Mar 7, 2023 · 3038 views
    This topic created in 1299 days ago, the information mentioned may be changed or developed.

    一张表,结构简单

    CREATE TABLE `zp_category_relation` (
      `id` bigint(20) NOT NULL,
      `aid` bigint(20) NOT NULL COMMENT '文章 id',
      `cid` bigint(20) NOT NULL COMMENT '分类 id',
      `extend` json DEFAULT NULL COMMENT '扩展字段',
      PRIMARY KEY (`id`),
      UNIQUE KEY `acr_ac_uidx` (`aid`,`cid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='分类的关系';
    

    其中一条数据为:

    INSERT INTO `zp_category_relation` (`id`, `aid`, `cid`, `extend`) VALUES (393388343615493, 393060164034565, 393041089290245, '{\"393041089290245\": [{\"key\": \"type\", \"value\": \"3\"}]}');
    

    想查出 extend 列中,key=type 的数据,用的如下 sql 语句

    SELECT * FROM `zp_category_relation` WHERE  extend->"$[*].key" = "type";
    

    结果为空,求教更准确的 sql 语句

    9 replies  •  2023-03-08 13:33:05 +08:00
    tedzhou1221
        1
    tedzhou1221  
       Mar 7, 2023
    拿 json 的内容 出来看看, {"393041089290245": [这里是数组]}
    xiaoxixi
        2
    xiaoxixi  
       Mar 7, 2023
    SELECT * FROM `zp_category_relation` WHERE JSON_EXTRACT(extend, '$**.key') = "type";
    OutOfMemery
        3
    OutOfMemery  
       Mar 7, 2023
    SELECT
    *
    FROM zp_category_relation a,
    JSON_TABLE (a.extend, '$.*[*]' COLUMNS ( type text PATH '$.key', value int PATH '$.value') ) AS t
    where t.type='type'
    sunmoon1983
        4
    sunmoon1983  
    OP
       Mar 7, 2023
    @tedzhou1221 json 的内容
    ```
    {"393041089290245": [{"key": "type", "value": "3"}]}
    ```
    sunmoon1983
        5
    sunmoon1983  
    OP
       Mar 7, 2023
    @OutOfMemery 感谢,这个 SQL 能查出来
    sunmoon1983
        6
    sunmoon1983  
    OP
       Mar 7, 2023
    @xiaoxixi 查不出来呀
    sunmoon1983
        7
    sunmoon1983  
    OP
       Mar 8, 2023
    @OutOfMemery 不对呀,Mysql5.7 中好像不能用?
    OutOfMemery
        8
    OutOfMemery  
       Mar 8, 2023
    @sunmoon1983 #7 8.0 版本才行,话说你这是单纯的想匹配这个 key 么,那直接用 like 呗

    ```sql
    select * from zp_category_relation where extend like '%"key": "type"%'
    ```
    Boyce
        9
    Boyce  
       Mar 8, 2023
    ```sql
    SELECT * FROM `zp_category_relation` WHERE JSON_EXTRACT(extend, '$**.key') = JSON_ARRAY('type');
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1005 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: f77a3b4c · 29ms · UTC 23:21 · PVG 07:21 · LAX 16:21 · JFK 19:21
    ♥ Do have faith in what you're doing.