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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题