MySQL字符串處理之一個(gè)字段包含多個(gè)ID的解決
如果在MySQL中一個(gè)表中存著一個(gè)字段包含多個(gè)Id,應(yīng)該如何處理呢,下面就為您介紹這種MySQL字符串問(wèn)題的處理方法,希望對(duì)您學(xué)習(xí)MySQL字符串方面能有所幫助。
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。
#錯(cuò)誤的方法
- 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會(huì)出現(xiàn)當(dāng)ID大于10的時(shí)候,查ID為1的數(shù)據(jù),會(huì)把1,10,11,12......的都拿出來(lái)。
4、擴(kuò)展會(huì)出現(xiàn)的問(wèn)題。
用FIND_IN_SET可以解決ID是用","號(hào)隔開(kāi)的問(wèn)題。然而會(huì)有另外的兩種情況。
A、當(dāng)ID不包含",",但是用別的符號(hào)分開(kāi)時(shí),如用"|"。我們有如下的解決辦法
- select *
- from Category
- where (select FIND_IN_SET(cateId,REPLACE(cateIds,'|',',')) from OpenRecord where opreId=1)
以上就是該MySQL字符串問(wèn)題的處理方法。
【編輯推薦】