【问题标题】:Php genarate data from table 1 to table 2 but will duplicate after 1000 rowsphp从表1到表2生成数据但是1000行后会重复
【发布时间】:2021-11-08 13:33:24
【问题描述】:

我想创建一个函数来生成随机排名。我有一个成员表调用t1_user,当我的第二个表t2_rank 为空时,我想从t1_user 调用ORDER BY RAND()

我的t1_user 表有 5400 行数据,所以我想像每 500 行数据一样拆分数据然后REPLACE INTO。我正在使用Discuz! 模板语言。

我的t1_user 数据(5400 条记录+,无重复)

+--------------------+
| id      | name     |
+--------------------+
| 1       | abc      |
| 2       | hahaha   |
| 3-999.....         |
| 1000    | abcdef   |
| 1001    | ohyeah   |
| 1002    | nci      |
----------------------

在我运行我的代码后,会将以下数据插入到我的t2_rank 表中

+---------+----------+--------+
| id      | name     | rank   |
+-----------------------------+
| 1       | abc      | 1      |
| 2       | hahaha   | 2      |
| 1000    | abcdef   | 1000   | //until here is fine
| 1001    | abc      | 1001   | //wrong, will insert data of row1 and continue data of row2...
| 1002    | hahaha   | 1002   |
+-----------------------------+

我目前的编码如下。

$checkfirst = DB::result_first("SELECT count(*) cnt FROM ".DB::table('t2_rank').""); //template language DB::
if($checkfirst == 0){
    $s = DB::fetch_all("SELECT * FROM ".DB::table('t1_user')." ORDER BY RAND();");
    $x = 1;
    foreach($s as $su){
        $newdata[$x] = '('.$x.','.$id.')';
        $x++;
    }
        
    $pagesplit = 500;//500 row split
    $firstpage = 0;
    $tpp = $pagesplit;
    $runningtime = ceil(count($s)/$pagesplit);      

    for($y=1;$y<$runningtime;$y++){
        $genewdata = array_slice($newdata, $firstpage, $tpp);
        $tobeupdate = implode(',',$genewdata);
        DB::query("REPLACE INTO ".DB::table('t2_rank')." (rank,id) VALUES ".$tobeupdate."");
                    
        $firstpage = $firstpage+$pagesplit;
        $tpp = $tpp+$pagesplit;
        if($tpp >= count($s)){
            $tpp = count($s);
        }
    }
}

我可以知道我的代码有什么问题吗?谢谢。

【问题讨论】:

    标签: php mysql arrays slice


    【解决方案1】:

    您希望一次更新 500 行数据。您这样做的代码相当复杂。这样你就可以了解正在发生的事情。您似乎混淆了 $tpp$firstpage 变量。难怪,鉴于他们的名字。这是我的建议:

    $totalRowCount = count($s);
    $replaceCount = 500;
    for ($offset = 0; $offset < $totalRowCount; $offset = $offset + $replaceCount) {
        $replaceData = array_slice($newdata, $offset , $replaceCount);
        DB::query("REPLACE INTO " . DB::table('t2_rank') . 
                  " (rank,id) VALUES " . implode(',', $replaceData));
    }
    

    我无法对此进行测试,但我认为您可以看到我在尝试做什么?

    【讨论】:

    • 是的,其实我对array_slice()的理解是错误的,我以为$offset$replaceCount是我要切片的范围,但实际上$replaceCount是数量(多少)我会喜欢从$offset开始。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多