0

OK the question is NOT about how to return the ID, but more like how to skip it... I have a situation where i use last_insert_id() to get the id of the last inserted row, but i want to get a zero if no row is inserted. The problem is as follows:

  • i insert...update a few records: all IDs are returned since the rows are freshly inserted
  • then i repeat the process: this time IDs are not returned. YAY! that's exactly what i want
  • i change one column value and repeat the process: but now the ID is returned for the row i've changed the column value in. And this is making me very angry. I don't want mysql to return the ID at all if it's not inserting anything

so to sum up:

  • when inserting new records: IDs are returned
  • when inserting identical records: IDs are not returned
  • when updating a value: updated IDs of the updated rows are returned :(

Is there a workaround for this?

I know this happens because mysql probably does not perform an update on identical records, but still ... i'd sure like to know how to work around this.

Marius
  • 3,976
  • 5
  • 37
  • 52
  • If I'm not mistaken, at least for most APIs, an INSERT should return the *number* of rows inserted. You should be able to use this to determine if anything was inserted. – ScoPi Nov 28 '12 at 13:00
  • Looks like ROW_COUNT() might give you that if you're doing "raw" queries. – ScoPi Nov 28 '12 at 13:01
  • @ScoPi provide it as an answer - i'll click accept on it. Looks like mysql has a special behaviour for this particular query when checking ROW_COUNT() so this should work. Thanks. – Marius Nov 28 '12 at 13:05
  • http://stackoverflow.com/questions/778534/mysql-on-duplicate-key-last-insert-id – Timo Huovinen Nov 20 '14 at 09:22

1 Answers1

0

You should be able to retrieve the number of rows inserted and use that to determine if anything was inserted. If you're using "raw" queries (i.e. no API that might otherwise provide the number of rows inserted), it looks like ROW_COUNT() might give you what you want.

ScoPi
  • 1,193
  • 9
  • 14
  • 1
    To be more specific - in this situation, row count will return 1 if a row was inserted, 2 if a row was updated and 0 if it was an identical match to an existing record (so neither insert nor update). – Marius Nov 28 '12 at 13:15