使用子查询将mysql表插入另一个表中

时间:2014-03-24 11:43:19

标签: php mysql

我正在使用PHP将包含两列的CSV导入到现有表中(我正在使用Joomla / Virtuemart)

现有表中的列是id(用户ID)和product_id。

CSV文件中的列是product_sku和用户名,因此我需要先加入相应的表,以便将id(用户ID)与用户名匹配,并将proudct_sku与product_id相匹配。 我还需要修剪用户名的前导零,以及我使用sql完成的productsku中的空格。

我创建了一个包含CSV中数据的临时表,然后将其连接到两个表中。我已经获得了我需要的数据,但现在需要将该数据插入到现有表中。理想情况下,我想用mySQL做这个,是否可以将其作为子查询?

速度会有很大差异吗?

function do_query($file)
{

   //  $sql = "LOAD DATA INFILE ".$file['tmp_name']." INTO TABLE FavouritesTmp FIELDS TERMINATED BY ','  LINES TERMINATED BY '\n' (data1, data2)";

   $sql = "CREATE TEMPORARY TABLE FavouritesTmp (
                productsku VARCHAR(50) NOT NULL, 
                user VARCHAR(50) NOT NULL
        )";
   $this->_db->setQuery($sql);
   $this->_db->query();
   $handle = fopen($file['tmp_name'], "r");
   do
   {
      if ($data[0])
      {
         $sql = "INSERT INTO `FavouritesTmp` (productsku, user) VALUES 
                    ( 
                        '" . $data[0] . "', 
                        '" . $data[1] . "'
                    ) 
                ";
         $this->_db->setQuery($sql);
         $this->_db->query();
      }
   }

   while ($data = fgetcsv($handle, 1000, ",", "'"));
   $sql = "SELECT TRIM(LEADING  '0' FROM user) AS username, 
        productsku AS productsku, 
        jos_users.id AS id, 
        jos_vm_product.product_id AS product_id 
        FROM FavouritesTmp 
        LEFT JOIN jos_users ON (  TRIM(LEADING  '0' FROM username ) = jos_users.username )
        LEFT JOIN jos_vm_product ON  TRIM(productsku) = jos_vm_product.product_sku";
   $this->_db->setQuery($sql);
   print_r($this->_db->loadAssocList());
}

1 个答案:

答案 0 :(得分:1)

您可以使用insert . . . select语法:

INSERT INTO ExistingTable(username, productsku, id, product_id)
    SELECT TRIM(LEADING  '0' FROM user) AS username, 
           productsku AS productsku, 
           jos_users.id AS id, 
           jos_vm_product.product_id AS product_id 
    FROM FavouritesTmp 
    LEFT JOIN jos_users ON (  TRIM(LEADING  '0' FROM username ) = jos_users.username )
    LEFT JOIN jos_vm_product ON  TRIM(productsku) = jos_vm_product.product_sku;