문제

Possible Duplicate:
Normalized DB insertions

Is it possible to do a single query that will look for a record and either return it's ID or insert it and return it's ID? Here's what I was thinking may work for this:

INSERT INTO firstname (id, name) VALUES (NULL,'$name') 
ON DUPLICATE KEY UPDATE name ='$name', id=LAST_INSERT_ID(id)

If it helps, I'm using ezSQL and could just do a $db->query("..."); then an $id = $db->insert_id; to grab the insert id and use it in a variable.

도움이 되었습니까?

해결책

You can write your own stored procedure which will check for existing record.

  1. Try to retrieve the record by its id
  2. Check if it is null, insert it
  3. Otherwise you got the row

다른 팁

I'm not sure if I understand what do you need.

After calling INSERT INTO ... ON DUPLICATE KEY UPDATE ... you just simply need to get last_insert_id() from database and this should be all.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top