新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
MySQL字符串處理之一個字段包含多個ID的解決
如果在MySQL中一個表中存著一個字段包含多個Id,應(yīng)該如何處理呢,下面就為您介紹這種MySQL字符串問題的處理方法,希望對您學(xué)習(xí)MySQL字符串方面能有所幫助。

創(chuàng)新互聯(lián)公司主營博愛網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā),博愛h5微信小程序開發(fā)搭建,博愛網(wǎng)站營銷推廣歡迎博愛等地區(qū)企業(yè)咨詢
1、新建表
- drop table if exists Category;
- create table Category
- (
- cateId int(5) not null AUTO_INCREMENT,
- chiName varchar(80),
- primary key (cateId)
- );
- drop table if exists OpenRecord;
- create table OpenRecord
- (
- opreId int(5) not null AUTO_INCREMENT,
- cateIds varchar(80),
- primary key (opreId)
- );
2、初始化數(shù)據(jù)
- insert Category(chiName) values ('fish'),('shrimp'),('crab'),('tiger');
- insert OpenRecord(cateIds) values('1,2');
- insert OpenRecord(cateIds) values('2,3');
3、查詢OpenRecord中Id為1包括的Category。
#錯誤的方法
- select *
- from Category
- where (select INSTR(cateIds,cateId) from OpenRecord where opreId=1)
#正確的方法
- select *
- from Category
- where (select FIND_IN_SET(cateId,cateIds) from OpenRecord where opreId=1)
用INSTR會出現(xiàn)當(dāng)ID大于10的時候,查ID為1的數(shù)據(jù),會把1,10,11,12......的都拿出來。
4、擴展會出現(xiàn)的問題。
用FIND_IN_SET可以解決ID是用","號隔開的問題。然而會有另外的兩種情況。
A、當(dāng)ID不包含",",但是用別的符號分開時,如用"|"。我們有如下的解決辦法
- select *
- from Category
- where (select FIND_IN_SET(cateId,REPLACE(cateIds,'|',',')) from OpenRecord where opreId=1)
以上就是該MySQL字符串問題的處理方法。
分享標(biāo)題:MySQL字符串處理之一個字段包含多個ID的解決
本文地址:http://fisionsoft.com.cn/article/djgjeip.html


咨詢
建站咨詢
