PHP 插入大數據優化

/*public function index()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        for ($i=200001; $i<300000; $i++) {

            $sql = "insert into think_test(name) values ($i)";
            Db::query($sql);

        }

        $time2 = microtime(true);

        echo $time1-$time2; //42.355000019073s
    }*/

    public function index()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        $sql = "insert into think_test(name) values ";
        for ($i=0; $i<1000000; $i++) {

            $sql .= "($i),";
        } //insert into think_test(name) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),

        //insert into think_test(name) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)
        $sql = substr($sql, 0, -1);

        Db::query($sql);

        $time2 = microtime(true);

        echo $time2-$time1; //5s
    }

    /**
     *
     * @DESC: 循環插入1000000 條數據 只須要5s左右 批量插入
     *
     * @author: HX
     * @Time: 2018/9/26   12:00
     *
     */
    public function index2()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        //循環插入一百萬
        for ($i=10000; $i <10010000 ; $i+=10000) {
            # code...
            $j = $i-10000;
            $sql = "insert into think_test(name) values ";
            for ($y=$j; $y<$i; $y++) {

                $sql .= "($y),";
            }
            $sql = substr($sql, 0, -1);

            Db::query($sql);
            unset($sql);
        }

        $time2 = microtime(true);

        echo $time2-$time1;
    }
相關文章
相關標籤/搜索