duanruoyu6675 2015-04-22 20:52
浏览 184
已采纳

SQL选择具有多个值和可变数据

I have a table that contains a Job Number field (jobno). This field contains data that looks like '123456' or it could look like '345678 Acme'. Users of the website will type in a request for a job number. I have no problem searching and returning the desired data using a simple SELECT - WHERE - LIKE command. My problem is, users want to be able to now enter multiple Job numbers in their request field. i.e.: 123456, 345678. Etc.

How would I go about creating a select for this? I understand the use of the "WHERE jobno IN" and this method works fine for job numbers that are only a number. However, this does not allow for wildcards therefore I'm unable to return data such as '345678 Acme'. Also, I cannot use a series of "OR" because I would not know how many job numbers the user might enter to search for.

I hope this is enough explanation. Any help would be great. Thanks!

  • 写回答

3条回答 默认 最新

  • doushi1473 2015-04-22 21:03
    关注

    You should first do an explode of the input from the user. Then you have different options of what you could do, you could run a query for each number, and then just add all the resulting rows to an array (you could get duplicated results), or you could build the query on the fly.

    Example:

    // Input $_POST['jobNo'] = '123,1234,abc,abcde'
    $str = $_POST['jobNo'];
    $pieces = explode(',',$str); // returns array("123","1234","abc","abcd")
    $sql = "SELECT * FROM table WHERE (";
    $i = 0;
    foreach( $pieces as $piece )
    {
        if( $i !== 0 )
            $sql .= 'OR ';
        $sql .= "column LIKE '%". $piece ."%' ";
        $i++;
    }
    if( $i === 0 )
        $sql .= "1 = 1";
    
    $sql .= ")";
    
    // $sql = SELECT * FROM table WHERE (column LIKE '%123%' OR column LIKE '%1234%' OR column LIKE '%abc%' OR column LIKE '%abcd%') 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计