mysql中 where in 用法详解

这里分两种情况来介绍

1、in 后面是记录集,如:

select  *  from  table  where   uname  in(select  uname  from  user); 

2、in 后面是字符串,如:

select  *  from  table  where   uname  in('1','2','3');

注意:这里一定要将字符串用单引号''单个 标注起来;

也可以定义变量
$_str = '1,2,3';
select  *  from  table  where   uname  in($_str);

但严禁在in内用两个单引号,会遇到sql语句错误,如下

select  *  from  table  where   uname  in('1,2,3');

3、in 后面是数组,其实也就是第二种方法,只不过把需要把数组转换成像第二种方法那样的字符串形式:

//$pieces是含数据的数组

for($i=0;$i<count($pieces);$i++){

  $uname=$uname."'".$pieces[$i]."',";   //将数组转换成字符串,并且以豆号分隔

}

$the_uname ="uname in(".$uname."'')"; //减去字符串的最后一个豆号

select  *  from  table  where    ".$the_uname." ;

备注:这种方法的原理其实很简单,二就是把数组编程上面“第2种情况”的形式

原文地址:https://www.cnblogs.com/xccjmpc/p/4147797.html