我正在尝试在下面的代码中执行以下操作:
从wrnt表中获取“ est_no,wo_no,wt_no”。
从wrnt表中获取的每个est_no,从最旧表中获取“ itemcode”
如果“ itemcode”具有SE前缀,那么我将递归调用该函数,直到没有前缀为止
获取“ itemcode”后,我从itemast表中获取了每个itemcode的相关“ marate”
最后将它们全部插入(wo_no,wt_no,itemcode,marate)
您会看到有很多循环和递归,导致运行时间很多。
有什么办法可以避免循环吗?或任何其他方式来优化脚本?
<?php
set_time_limit(200);
Class Matewr{
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
private $conn;
private $dsn;
private $pdo;
private $insertquery='replace into compcost.matewr (workord,warrant,itemcode,marate)';
function MateWr(){
$this->dbhost = 'localhost';
$this->dbuser = 'root';
$this->dbpass='';
$this->dbname = 'compcost';
$this->dsn="mysql:host=$this->dbhost;dbname=$this->dbname";
$this->pdo= new PDO ($this->dsn, $this->dbuser, $this->dbpass);
}
function readWrnt(){
$idresult = $this->pdo->query("SELECT est_no, wo_no, wt_no from compcost.wrnt");
while($row= $idresult->fetch())
{
$est_no=$row['est_no'];
$wo_no= $row["wo_no"];
$wt_no= $row["wt_no"];
$this->getItemCodesRecursive($est_no, $wo_no, $wt_no);
$this->pdo->query($this->insertquery);
}
}
function getItemCodesRecursive($est_no, $wo_no, $wt_no){
#$sql = "select itemcode, reccd from compcost.matest where est_no='".$est_no."'";
$sql =$this->pdo->prepare("select itemcode from compcost.matest where est_no=?");
$sql->execute(array($est_no));
$rows = $sql->fetchAll();
foreach($rows as $row){
$itemcode = $row["itemcode"];
if(strcasecmp(substr($itemcode, 0, 2),"se") == 0){
$this->getItemCodesRecursive(substr($itemcode, 2), $wo_no, $wt_no);
}
else{
$sql_marate=$this->pdo->prepare("select MARATE from compcost.itemmast where itemcode=?");
$sql_marate->execute(array($itemcode));
#$result_marate = $this->pdo->query($sql_marate);
#if($row_marate=$result_marate->fetch(PDO::FETCH_LAZY)){
$row_marate=$sql_marate->fetchAll();
foreach($row_marate as $row){
$marate=$row["MARATE"];
$this->insertquery .= " values ('$wo_no','$wt_no','$itemcode','$marate'),";
}
}
}
}
}
$matewr = new MateWr();
$matewr->readWrnt();
?>
感谢和问候
最佳答案
为什么不这样组合选择语句?
Select MARATE from compcost.itemmast a, compcost.matest b, compcost.wrn c WHERE c.wt_no = b.wt_no AND a.item_code = b.item_code
在表结构上不清楚,但要点...从上一个表(a)中选择一项,其中a = b的字段和b = c的字段。
这样,您无需循环就可以获取所有记录。
您可能还需要其他一些MySQL语句,但是通过使用sql语句,可以避免许多循环。