php - INSERT if not exists, else return id -


there limitations:

  1. cannot modify database
  2. columns not unique
  3. needs return last insert id (returning id)
  4. if exists, return existing id
  5. it called through our custom db library (the values in select parameters php (?, ?, ?, !))

insert tags (name, color, groupid) select  'test', '000000', 56 not exists (   select text tags name = 'test' , groupid = 56 ) returning id 

this works - until point need existing id aswell. inserted id. possible return value of select statement if doesn't insert?

update:

do $$ begin     if not exists (       select text tags name = 'test' , groupid = 56     )           insert tags (name, color, groupid)           values  ('test', '000000', 56) returning id;     else       return select text tags name = 'test' , groupid = 56;     end if; end $$ 

was testing kind of format - ends few errors:

return cannot have parameter in function returning void 

you can using cte.

the info cte has source data, replace values there placeholders php.

the cte return results first half of union if existing record exists (so show old id), , second half if insert performed (so show new id).

with info (name, color, groupid)   (values('test','000000',56)),   trial (     insert tags(name, color, groupid)       select info.name, info.color, info.groupid       info       not exists (         select * tags t2         t2.name = info.name , t2.groupid= info.groupid)     returning id) select tags.id tags inner join info on tags.name = info.name , tags.groupid= info.groupid union select trial.id trial; 

sql fiddle example: http://sqlfiddle.com/#!15/a7b0f/2

postgres manual page using ctes

http://www.postgresql.org/docs/9.1/static/queries-with.html


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -