Pregunta

I have following table

id  val     match_id    oddname_id    dif
1   1.75    401             1         0.25 //THIS ONE MUST BE DELETED. EXPLAINED BELOW
2   3.30    401             2         -0.20
3   5.00    401             3         0.00
4   1.13    401             4         0.00

Id is just index. And primary key is oddname_id and match_id together.

I parse data from xml and here is what I must to do:

  1. INSERT if PRIMARY KEY NOT EXISTS.

    When I have match_id=402 and oddname_id=1 I must insert, because match_id 402 doesn't exists.

  2. ON DUPLICATE KEY UPDATE.

    When I have match_id=401 and oddname_id=1 i must update only val and dif. (dif equals difference of val and it's new value.

  3. I want to delete all data if KEY DOESN'T EXISTS

Here's my query; first two statements works fine, but I have no opinion how I'll make 3rd one to work:

INSERT INTO odds 
    (match_id,oddname_id,val) 
VALUES 
    ('401','2','3.3'),
    ('401','3','5.0'),
    ('401','4','1.25'),
ON DUPLICATE KEY 
UPDATE 
    dif = val-VALUES(val), 
    val = VALUES(val);

I Want to add to this query something like this:

IF KEY DOESN'T EXISTS DELETE.

in this example it must delete first row:

 id val     match_id    oddname_id    dif
 1  1.75    401             1         0.25

Because I have not 401 (match_id) and 1 (oddname_id) in VALUES while inserting.

¿Fue útil?

Solución

  1. Import data from the XML file in an additional (temporary) table - you could use LOAD XML command in MySQL 5.5.
  2. Delete records from the odds table which do not exist in the temp. table - use DELETE with JOIN command.
  3. Insert/Update the odds table with data from temp. table - use INSERT...ON DUPLICATE KEY UPDATE command.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top