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