我有一个使用cvs importer将数据插入mysql的函数有问题的原始代码如下:
{
$sql = "LOAD DATA INFILE '".@mysql_escape_string($this->file_name).
"' INTO TABLE `".$this->table_name.
"` FIELDS TERMINATED BY '".@mysql_escape_string($this->field_separate_char).
"' OPTIONALLY ENCLOSED BY '".@mysql_escape_string($this->field_enclose_char).
"' ESCAPED BY '".@mysql_escape_string($this->field_escape_char).
"' ".
($this->use_csv_header ? " IGNORE 1 LINES " : "")
."(`".implode("`,`", $this->arr_csv_columns)."`)";
$res = mysql_query($sql);
$this->error = mysql_error();
}
我的问题是我如何才能做到这一点,如果只有更新记录到该表而不重新插入新记录,因为我想插入多个记录,然后再次上传它们,但首先上传#LL null然后更新将采用值
答案 0 :(得分:0)
看起来像MySQL has support for temporary tables,因此一种解决方案是将CSV数据插入临时表,然后将其加入永久数据以确定要更新的行。
简化示例(假设您的目标表名为datatable
,主键为data_id
,列field_a
和field_b
):
CREATE TEMPORARY TABLE temp_bulk_inserted_datatable LIKE datatable;
LOAD DATA INFILE '/path/to/data.csv' INTO TABLE temp_bulk_inserted_datatable;
-- Update rows that already exist with new data from the file
UPDATE
datatable as OLD
JOIN
-- Inner Join, so that only matching rows will be touched
temp_bulk_inserted_datatable as NEW
ON OLD.data_id = NEW.data_id
SET
OLD.field_a = NEW.field_a,
OLD.field_b = NEW.field_b;
-- Insert new rows from the CSV file which don't yet exist
INSERT INTO datatable
( data_id, field_a, field_b )
SELECT
NEW.data_id, NEW.field_a, NEW.field_b
FROM
temp_bulk_inserted_datatable as NEW
LEFT JOIN
-- Left Outer Join: we want to know about non-matches...
datatable as OLD
ON OLD.data_id = NEW.data_id
WHERE
-- ...in fact, we want ONLY the non-matches
OLD.data_id IS NULL;
DROP TABLE temp_bulk_inserted_datatable;
(请注意,我实际上并没有使用MySQL,所以我的一些语法可能略有偏差,但从我在手册中读到的内容来看,上面应该是正确的。)