I'm Importing a CSV with two columns into an existing table using PHP (I'm using Joomla/Virtuemart)
The columns in the existing table are id (user id) and product_id.
The columns from the CSV file are product_sku and username so I need to first join to the appropriate tables to match the id (user id) with the username, and proudct_sku to product_id. I also need to trim leading zeros off the username, and whitespace from the productsku which I've done using sql.
I created a temporary table containing the data in the CSV, then joined onto both tables. I've got the data I need back but now need to insert that data into the existing table. Ideally I'd like to do this with mySQL, is it possible to do this as a sub query?
Would there be a massive difference in speed?
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());
}
You can just use insert . . . select
insert . . . select
insert . . . select
syntax:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.