mysql json 数组怎么搜索

在MySQL中,可以使用JSON_CONTAINS函数来搜索JSON数组中的元素。这里有一个简单的例子:

假设有一个名为items的表,其中有一个名为attributes的列,包含JSON数组。

bash 复制代码
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    attributes JSON
);


INSERT INTO items (attributes) VALUES
('["apple", "banana", "cherry"]'),
('["banana", "cherry", "date"]'),
('["apple", "banana", "date"]');

如果你想要搜索包含"banana"的attributes,可以使用以下查询:

bash 复制代码
SELECT * FROM items
WHERE JSON_CONTAINS(attributes, JSON_OBJECT('key', 'banana'));

JSON数组

bash 复制代码
INSERT INTO items (attributes) VALUES
('[1, 2, 3]'),
('[1, 104, 101]'),
('[102, 101, 202]');

如果要查询包含 101 这个数字的 attributes

bash 复制代码
SELECT * FROM `items` 
WHERE JSON_CONTAINS(`attributes`, CAST(101 AS JSON))
相关推荐
FYKJ_201012 小时前
springboot雅集社区养老管理系统04456-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_201012 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
javascript·vue.js·spring boot·mysql·typescript·spark·express
FYKJ_201012 小时前
springboot羽毛球场地管理系统00626-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_201013 小时前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
IT枫斗者枫哥18 小时前
MyBatis一对多分页:LIMIT 20,为什么凑不齐20个订单?
java·数据库
Flynt18 小时前
"MySQL搜不动就上ES"?我先在50万行数据上测了它自带的ngram全文索引
mysql·elasticsearch·搜索引擎
Y0018 小时前
PostgreSQL 的锁:为什么你的 ALTER TABLE 会卡住,以及怎么查
数据库·postgresql
imDwAaY19 小时前
Redo Log 和 Binlog 为什么需要两阶段提交?
后端·mysql
灰原喜欢柯南19 小时前
OceanBase 运维管理知识点——OCP 监控、诊断与变更控制
数据库·oceanbase
码农-00419 小时前
Springboot 集成 Ehcache操作数据库显示SQL语句设置
数据库·spring boot·sql