MySQL字符串处理之一个字段包含多个ID的解决

如果在MySQL中一个表中存着一个字段包含多个Id,应该如何处理呢,下面就为您介绍这种MySQL字符串问题的处理方法,希望对您学习MySQL字符串方面能有所帮助。

1、新建表

 
 
 
  1. drop table if exists Category;  
  2. create table Category  
  3. (  
  4.     cateId                         int(5)                         not null AUTO_INCREMENT,  
  5.     chiName                        varchar(80),  
  6.    primary key (cateId)  
  7. );  
  8.  
  9. drop table if exists OpenRecord;  
  10. create table OpenRecord  
  11. (  
  12.     opreId                         int(5)                         not null AUTO_INCREMENT,  
  13.     cateIds                        varchar(80),  
  14.    primary key (opreId)                      
  15. );  

2、初始化数据

 
 
 
  1. insert Category(chiName) values ('fish'),('shrimp'),('crab'),('tiger');  
  2.  
  3. insert OpenRecord(cateIds) values('1,2');  
  4. insert OpenRecord(cateIds) values('2,3');  

3、查询OpenRecord中Id为1包括的Category。

#错误的方法

 
 
 
  1. select *   
  2.     from Category  
  3.     where (select INSTR(cateIds,cateId) from OpenRecord where opreId=1

#正确的方法

 
 
 
  1. select *   
  2.     from Category  
  3.     where (select FIND_IN_SET(cateId,cateIds) from OpenRecord where opreId=1

用INSTR会出现当ID大于10的时候,查ID为1的数据,会把1,10,11,12......的都拿出来。

4、扩展会出现的问题。
用FIND_IN_SET可以解决ID是用","号隔开的问题。然而会有另外的两种情况。

A、当ID不包含",",但是用别的符号分开时,如用"|"。我们有如下的解决办法

 
 
 
  1. select *   
  2.     from Category  
  3.     where (select FIND_IN_SET(cateId,REPLACE(cateIds,'|',',')) from OpenRecord where opreId=1)  

以上就是该MySQL字符串问题的处理方法。

 

 

【编辑推荐】

带参数的MySql存储过程

查看三种MySQL字符集的方法

带您深入了解MySQL默认字符集

MySQL删除外键定义的方法

使用MySQL外键的四个条件

 

THE END