dongwang6837 2018-10-04 09:44
浏览 87
已采纳

如何在选择基于两个数组数据的查询时避免循环

I have a table like below.

id  supplier_id item_id minimum_order_qty   
1      6           1         500 
2      4           1         300 
3      2           2         200 
4      3           2         100 
5      4           3         250 
6      5           5         100 
7      7           6         1000    
8      8           6         600 
9      9           7         700 
10     1           7         500 
11     7           8         1000    
12     9           9         700 
13     2           10        500 
14     9           10        600 

Each item_id can have more than one supplier(supplier_id).

I have two array item_id array and supplier_id array.

item_id array:

Array
    (
        [0] => 9
        [1] => 10
        [2] => 11
        [3] => 12
        [4] => 13
        [5] => 14
        [6] => 15
        [7] => 16
        [8] => 17
        [9] => 18
        [10] => 19
        [11] => 20
        [12] => 21
        [13] => 22
        [14] => 23
        [15] => 24
    )

supplier_id array:

Array
        (
            [0] => 9
            [1] => 2
            [2] => 5
            [3] => 1
            [4] => 1
            [5] => 9
            [6] => 6
            [7] => 4
            [8] => 6
            [9] => 9
            [10] => 1
            [11] => 9
            [12] => 9
            [13] => 4
            [14] => 5
            [15] => 9
        )

Both array is same length. I want to select minimum_order_qty from supplier_item based on this two array. Normally, I have to select inside loop like this:

$item_count = count($item);
$sup_count = count($supp_id);
for($i=0; $i<$item_count; $i++) {
    $itm_id = $item[$i];
    $s_id = $supp_id[$i];
    $sql = "select * from supplier_item where item_id=$itm_id and supplier_id=$s_id";
    $result[] = $this->query($sql);
}

But, the above code will run query many times. I don't want to do this. So, Is there any other way to select data with single query?

  • 写回答

2条回答 默认 最新

  • dongshou1991 2018-10-04 09:56
    关注

    You can do it in one query

    $item_count = count($item);
    $sup_count = count($supp_id);
    $predicates = [];
    for($i=0; $i<$item_count; $i++) {
        $itm_id = $item[$i];
        $s_id = $supp_id[$i];
        $predicates[] = "(item_id=$itm_id and supplier_id=$s_id)";
    }
    $sql = "select * from supplier_item where " . implode(' OR ', $predicates);
    $result = $this->query($sql);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开