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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度