How to know if when using “on duplicate key update” a row was inserted or updated?

后端 未结 3 1295
-上瘾入骨i
-上瘾入骨i 2020-12-09 15:09

We have a database that gets updated everyday at midnight with a cronjob, we get new data from an external XML.

What we do is that we insert all the new content and

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 16:00

    I can say How I did in PHP:

    1) Simple query SELECT MAX(id) and remember it to $max_id from table before Insert On Duplicate.

    2) Then during the update process collect ID of affected rows (no mater new or existed): $ids[] = mysql_insert_id();

    3) Then $inserted_rows = max($ids)-$max_id;

    4) Updated rows = count($ids_srt)-$inserted_rows

    $max_id = mysql_query("SELECT MAX(id) from table");
    $max_id = mysql_result($max_id, 0);
    
    // !!! prepare here 'insert on duplicate' query in a cycle
    
    $result=mysql_query($query);
    $ids[] = mysql_insert_id();
    
    // finish inserting and collecting affected ids and close cycle
    
    $inserted_rows = max($ids)- $max_id;
    $updated_rows = count($ids)- $inserted_rows
    

提交回复
热议问题