前言
?最近在項目中遇到這樣一個需求:需要在數據表中檢索包含指定內容的結果集,該字段的數據類型為text,存儲的內容是json格式,具體表結構如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
create table `product` ( `id` int(11) unsigned not null auto_increment comment 'id' , `name` varchar(100) not null default '' comment '產品名稱' collate 'utf8mb4_general_ci' , `price` decimal(10,2) unsigned not null default '0.00' comment '產品價格' , `suit` text not null comment '適用門店 json格式保存門店id' collate 'utf8mb4_general_ci' , `status` tinyint(3) not null default '0' comment '狀態 1-正常 0-刪除 2-下架' , `create_date` datetime not null default current_timestamp comment '發布時間' , `update_date` datetime not null default current_timestamp on update current_timestamp comment '修改時間' , primary key (`id`) using btree ) comment= '產品表' collate= 'utf8mb4_general_ci' engine=innodb auto_increment=1 ; |
表數據如下:
現需求:查找 suit->hotel 中包含10001的數據。
通過谷歌百度查找,大致找到以下幾種方案:
方案一:
1
2
|
select * from product where suit like '%"10001"%' ; #like方式不能使用索引,性能不佳,且準確性不足 |
方案二:
1
2
|
select * from product where suit locate( '"10001"' , 'suit' ) > 0; # locate方式和like存在相同問題 |
方案三:
1
2
|
select * from product where suit != '' and json_contains( 'suit' -> '$.hotel' , '"10001"' ); #以mysql內置json函數查找,需要mysql5.7以上版本才能支持,準確性較高,不能使用全文索引 |
方案四(最終采用方案):
1
2
|
select * from product where match(suit) against( '+"10001"' in boolean mode); #可使用全文索引,mysql關鍵字默認限制最少4個字符,可在mysql.ini中修改 ft_min_word_len=2,重啟后生效 |
match() against() 更多使用方法可查看mysql參考手冊:
https://dev.mysql.com/doc/refman/5.6/ja/fulltext-boolean.html
總結
到此這篇關于mysql模糊查詢json關鍵字檢索方案示例的文章就介紹到這了,更多相關mysql json關鍵字檢索內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/zxw09332/article/details/121626111