views:

37

answers:

1

I'm loading files into a table with php. I create a table like this:

CREATE TABLE IF NOT EXISTS $table (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`order` INT DEFAULT 0,
`data` VARCHAR(200) UNIQUE KEY,
`cur_timestamp` TIMESTAMP DEFAULT NOW())"

And fill it from a text file like this:

LOAD DATA LOCAL 
INFILE '".$file ."' 
REPLACE INTO TABLE $table 
FIELDS TERMINATED BY '^' 
(`order`,`data`)"

I've also tried reading the file into an array and just using an INSERT .. ON DUPLICATE KEY

INSERT INTO $table (`order`,`data`)
VALUES ($parts[0],'$parts[1]') 
ON DUPLICATE KEY UPDATE `order` = '$parts[0]'

In both cases if data is the the same in the new and old record but order is different it INSERTs. I expect it to UPDATE if data is the same. I expect my tables not set up properly, but can't see what the problem is. Can anyone tell me why it doesn't UPDATE when data matches?

A: 
  1. You have to insert data including primary key- here id. In that case if old and new id are same, then data will be replaced- otherwise not. But your PK is AUTO_INC, so alternatively you can use an unique index column like order or anything else. For reference, please see - Replace

  2. To print an array content, you need to use {} like

    "INSERT INTO $table (order,data) VALUES ({$parts[0]},'{$parts1}') ON DUPLICATE KEY UPDATE order = '{$parts[0]}'"

    or concatenation

Hope this may help you

Sadat

Sadat
I guess I thought I was using "an unique index column" since data is set to UNIQUE. I'm not sure what you're suggesting I change.I put the {} around the arrays, didn't notice any change in output. I've definitely been reading the references. I must me missing something.
@Sadat I think @integris is right: according to the docs, ON DUPLICATE KEY is supposed to work for simple UNIQUE columns as well. Strange.
Pekka
both of you are right, i have missed that "UNIQUE KEY" of `data` column :(
Sadat