dougaojue8185 2016-01-15 10:59
浏览 132
已采纳

在for或foreach循环中执行此查询是不好的做法吗?

So I have the following query:

$resclients=$mysqli->query("SELECT id,client_name FROM clients WHERE id IN ($result[])");

And I am wondering, is it bad practice to execute the above query in a for or foreach-loop, does it hurt the MySQL server?

Or, is it better to do LEFT JOINS or INNER JOINS or RIGHT JOINS?

Forgot to add, the $result[] is actually a two dimensional array.

Show your array:

Array
(
    [0] => Array
        (
            [id] => 7
            [resclients] => 6,7,8,9,10,11,12,13,14,15
        )

    [1] => Array
        (
            [id] => 5
            [resclients] => 5
        )

    [2] => Array
        (
            [id] => 4
            [resclients] => 4
        )
)

Just a small portion of it.

  • 写回答

1条回答 默认 最新

  • dtntjwkl83750 2016-01-15 11:08
    关注

    You can use it as:

    // a testing multidimensional array
    $testArr = array(
            array(
                'one'=>1,
                'two'=>2,
                'three'=>3)
            );
    
    $yourIds = array();
    foreach ($testArr as $value) {
        foreach ($value as $finalVal) {
            $yourIds[] = $finalVal[];
        }   
    }
    
    $implodedIds = implode(",",$yourIds);
    echo "SELECT id,client_name FROM clients WHERE id IN ($implodedIds)";
    

    Result:

    SELECT id,client_name FROM clients WHERE id IN (1,2,3)
    

    Note that: this is basic idea how can you use without using query in a loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计