dongzuan4860 2016-10-09 12:18
浏览 26
已采纳

具有别名选择器的SQL IN运算符不起作用仅返回第一个匹配

Im trying to return a set of data with php where a specific id matches in a set of ids in the database.

i have to following code:

$id = 2;

$stmGetScoutUnits = $db->prepare('SELECT * FROM scout_units as su WHERE '.$id.' IN (su.greenhouse_ids) AND user_id = 1');

$stmGetScoutUnits->execute();

$scoutUnits = $stmGetScoutUnits->fetchAll(PDO::FETCH_OBJ);

var_dump($scoutUnits);

database looks a follow:

scout_units
+---------+---------------+-------+
| user_id | greenhouse_ids| name  |
+---------+---------------+-------+
|    1    | 1,2           | test  |
|    1    | 1,2           | test2 |
|    1    | 3,4           | test3 |
+---------+---------------+-------+

When i have id 1 it returns sql rows 1 and 2 but when i have id 2 it returns nothing. i have no id whats going on here? any idea?

  • 写回答

1条回答 默认 最新

  • duandong1963 2016-10-09 12:29
    关注

    What you need here is MySQL's FIND_IN_SET() function, so your query should be like this:

    SELECT * 
    FROM scout_units as su 
    WHERE FIND_IN_SET('.$id.', su.greenhouse_ids) 
    AND user_id = 1
    

    And your prepared statement should be like this:

    $stmGetScoutUnits = $db->prepare('SELECT * FROM scout_units as su WHERE FIND_IN_SET('.$id.', su.greenhouse_ids) AND user_id = 1');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里