【问题标题】:Insert a value into a table where the id matches the id of a given value in another table将值插入到表中,其中 id 与另一个表中给定值的 id 匹配
【发布时间】:2013-11-09 15:54:48
【问题描述】:

这是我的 mysql 表

表 oc_product:

product_id    model 

  36547      KTMTGRD1

表 oc_url_alias:

url_alias_id             query               keyword

956             product_id=36547    0-Hand-Meat-Grinder-LaCuisine

我的所有产品都在 oc_products 中。我需要使用 csv 文件中的所有产品数据填充 oc_url_alias:

Model,keyword

KTMTGRD1,0-Hand-Meat-Grinder-LaCuisine

所以基本上我需要从 csv 文件中获取 model# 并使用它在 oc_product 中查找 product_id。然后我必须检查它是否已经存在于 oc_alias_id 中,如果不存在,则插入一个包含数据的新行。

我不知道这是否可以单独使用 mysql 查询来完成,或者我需要 php 的帮助? 这是我需要一次性将我的商店转移到另一个购物车的事情。

【问题讨论】:

    标签: php mysql sql csv


    【解决方案1】:

    不要把事情复杂化,如果这是一次性的事情。只需编写一个小的 PHP 程序。 所以基本上你需要在 Mysql 中创建一个包含 2 列模型和关键字的临时表,并将 csv 文件中的所有记录转储到临时表中。

    在你的 PHP 程序中从这个临时表中读取并运行一个循环

    select * from temp_table;
    loop through all the records{
    
      select count(*) from oc_product where model_no = temp_table.model_no;
    
         if (count==0){
    
           insert into the new table;
    
         }     
    
    }
    

    希望能帮到你

    【讨论】:

      【解决方案2】:

      我认为子查询和 INSERT IGNORE... 语法 (http://dev.mysql.com/doc/refman/5.5/en/insert.html) 的组合在这里应该适合您。

      因此,如果 CSV 文件中当前行的值在 $model 和 $keyword 中,则如下所示:

      INSERT IGNORE INTO oc_url_alias (query, keyword)
          SELECT CONCAT('product_id=',product_id), '$keyword' 
          FROM oc_product WHERE oc_product.model 
          LIKE '$model';
      

      注意:您必须根据您使用的数据库访问方法找出插入 PHP 变量的最佳方法。最安全的方法是使用 MYSQLi 或 PDO 和准备好的语句,但如果不是这样,请在它们上运行 mysql_real_escape_string。永远不要相信任何数据,即使是你自己的。

      这应该会让你走上正轨,但你需要弄清楚细节。

      【讨论】:

        【解决方案3】:

        关于我的第一个答案。由于您将执行许多查询,因此这会稍微耗时。因此,或者您可以从 oc_product 表中读取所有记录,然后将其存储在一个数组中。然后在 temp_table 循环中,检查临时表中的型号是否存在于 oc_product 表数组中。如果存在则不插入,否则插入。

        select * from oc_product;
        $array = store product_id and model;
        
        select * from temp_table;
        loop through all the records{
        
        
          if (!model_no.exists[$array]){
        
             insert into the new table;
        
          }     
        
        } 
        

        【讨论】:

          猜你喜欢
          • 2016-01-09
          • 1970-01-01
          • 2015-10-27
          • 2021-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-13
          相关资源
          最近更新 更多