提问人:Swee Hong 提问时间:9/13/2021 更新时间:9/13/2021 访问量:28
Php 将数据从表 1 生成到表 2,但在 1000 行后会重复
Php genarate data from table 1 to table 2 but will duplicate after 1000 rows
问:
我想创建一个函数来生成一个随机排名。我有一个成员表调用,我想从我的第二个表是空的开始。t1_user
ORDER BY RAND()
t1_user
t2_rank
我的表有 5400 行数据,所以我想像每 500 行数据一样拆分数据。我正在使用模板语言。t1_user
REPLACE INTO
Discuz!
我的数据(5400 条记录+,无重复)t1_user
+--------------------+
| 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);
}
}
}
我可以知道我的代码有什么问题吗?谢谢。
答:
2赞
KIKO Software
9/13/2021
#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));
}
我无法测试这一点,但我想你可以看到我想做什么?
评论
0赞
Swee Hong
9/13/2021
是的,其实我理解错了,我以为是我想切片的范围,但实际上是我想从数量(多少)开始。谢谢。array_slice()
$offset
$replaceCount
$replaceCount
$offset
评论