290 字
1 分钟
MySQL8 JSON类型使用笔记
多值索引(MYSQL版本>=8.0.17)
JSONARRAY类型
创建
ALTER Table student ADD INDEX index_name((CAST( book_ids -> "$[*]" as SIGNED ARRAY)));查询
select * from student where JSON_CONTAINS(book_ids ->'$[*]','-1');select * from student where -1 MEMBER OF(book_ids ->'$[*]');select * from student where JSON_OVERLAPS(book_ids ->'$[*]',CAST('[1,-1]' AS JSON));JSONOBJECT类型
创建
ALTER TABLE customers ADD INDEX index_name( (CAST(custinfo ->'$.ids' AS UNSIGNED ARRAY)) );custinfo 的内容为
{ "user":"Bob", "ids":[94477,94536]}查询
SELECT * FROM customers WHERE 94507 MEMBER OF(custinfo->'$.ids');SELECT * FROM customers WHERE JSON_CONTAINS(custinfo->'$.ids', CAST('[94507,94582]' AS JSON));SELECT * FROM customers WHERE JSON_OVERLAPS(custinfo->'$.ids', CAST('[94507,94582]' AS JSON));查询数据使用参考
- MEMBER OF、JSON_CONTAINS、JSON_OVERLAPS 的符合条件的查询可使用多值索引,实际以执行计划为准
- 索引不支持用于表关联
- 不能结合前缀索引
- 不支持排序
动态SQL示例
<if test="post_ids != null and post_ids.size > 0 "> OR JSON_OVERLAPS(post_ids ->'$[*]',#{post_ids, typeHandler=com.xr.common.mybatis.handler.JsonListLongTypeHandler})</if><if test="user_id != null"> OR JSON_CONTAINS(user_ids ->'$[*]',CAST(#{user_id} AS CHAR) )</if>特别注意
JSON_CONTAINS(book_ids ->’$[*]’,‘-1’) 中,‘-1’ 是包含 JSON 数字的 SQL 字符串。第二个参数需能表示有效 JSON,不能一概理解为所有数值参数都必须手工加引号。
MEMBER OF 和 JSON_CONTAINS 的性能需要结合数据和执行计划判断,不能只凭函数名比较。
MySQL8 JSON类型使用笔记
https://www.klzy.me/posts/mysql8-json类型使用笔记/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 890 天
部分内容可能已过时