sql 字符串变为查询ID号

来源:互联网 发布:java接口和抽象类区别 编辑:程序博客网 时间:2024/04/30 11:45
 1、新建
  1. drop table if exists Category;  
  2. create table Category  
  3. (  
  4.     cateId                         int(5)                         not nulAUTO_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)  
 
 
 
 
原创粉丝点击