一张表,结构简单
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 语句
1
tedzhou1221 2023-03-07 18:55:19 +08:00
拿 json 的内容 出来看看, {"393041089290245": [这里是数组]}
|
2
xiaoxixi 2023-03-07 19:01:21 +08:00
SELECT * FROM `zp_category_relation` WHERE JSON_EXTRACT(extend, '$**.key') = "type";
|
3
OutOfMemery 2023-03-07 19:54:04 +08:00
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' |
4
sunmoon1983 OP |
5
sunmoon1983 OP @OutOfMemery 感谢,这个 SQL 能查出来
|
6
sunmoon1983 OP @xiaoxixi 查不出来呀
|
7
sunmoon1983 OP @OutOfMemery 不对呀,Mysql5.7 中好像不能用?
|
8
OutOfMemery 2023-03-08 10:29:27 +08:00
@sunmoon1983 #7 8.0 版本才行,话说你这是单纯的想匹配这个 key 么,那直接用 like 呗
```sql select * from zp_category_relation where extend like '%"key": "type"%' ``` |
9
Boyce 2023-03-08 13:33:05 +08:00
```sql
SELECT * FROM `zp_category_relation` WHERE JSON_EXTRACT(extend, '$**.key') = JSON_ARRAY('type'); ``` |