优化Yii2 MYSQL查询

时间:2018-11-02 12:45:18

标签: mysql yii2

我需要优化我的代码。它可以工作,但需要时间,有时甚至会超时。

从表1和表2中选择的目标列必须合并到另一个表中。新表中不允许重复。 TIA

 $modelsc=Customers::find()->select('customer_id')->all();
 $modelsp = Product::find()->select('product_no')->all();
 foreach($modelsc as $modelc) {                                                                      
     $user = $connection->createCommand(
           'SELECT product_no as product_no,:cust_no as fkcustomer_id                                                                                                         
             FROM product AS p                                                                                                           
             WHERE NOT EXISTS( SELECT pc.fkproduct_no                                                                                                                         
             FROM                                                                                                                               
             productcustomer AS pc
             WHERE
            pc.fkproduct_no = p.Product_no AND fkcustomer_id = :cust_no)');
      $user->bindValue(':cust_no', $modelc->customer_id);
      $modelsx = $user->queryAll();    
      Yii::$app->db->createCommand()->batchInsert('productcustomer', [ 'fkproduct_no', 'fkcustomer_id'], $modelsx)->execute();                                                          }

1 个答案:

答案 0 :(得分:0)

查看您的代码,您可以避免使用不存在子句,尝试在pc.fkproduct_no上使用左连接检出n为空

SELECT product_no as product_no,
      :cust_no as fkcustomer_id                                           
FROM product AS p   
LEFT JOIN  productcustomer AS pc ON  pc.fkproduct_no = p.Product_no 
    AND fkcustomer_id = :cust_no  
WHERE pc.fkproduct_no  is null

无论如何,请确保连接条件所在的列上具有正确的索引

对于表products在列Product_no上的索引

productcustomer(fkcustomer_id, fkproduct_no)的综合索引