0

我有一个使用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,该字段首先为空,然后更新将采用值

4

1 回答 1

0

看起来MySQL 支持临时表,因此一种解决方案是将 CSV 数据插入到临时表中,然后将其 JOIN 到永久数据以识别要更新的行。

简化示例(假设您的目标表名为datatable,有一个名为 的主键data_id,列field_afield_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,所以我的一些语法可能略有偏差,但从我在手册中阅读的内容来看,上述内容应该是正确的。)

于 2012-09-06T20:35:21.003 回答