Wert aus Tabelle lesen, wenn nicht vorhanden erstellen

charY

Benutzer
Beiträge
5
Ich suche nach einer Lösung einen Wert aus einer Tabelle auszulesen und falls er nicht vorhanden ist ihn in die Tabelle zu schreiben und mir die InsertID ausgeben zu lassen. Ist dies möglich mit MySQL?

Meine Suche hat bisher leider keinen Erfolg gehabt
 
Werbung:
Mir scheint, Du suchst diese Lösung:

Code:
test=# create table chary(key serial primary key, val text unique);CREATE TABLE
test=*# with ok as (select * from chary where val = 'blafasel'), neu as (insert into chary (val) values ('blafasel') on conflict do nothing returning *) select * from ok union all select * from neu;
 key |  val   
-----+----------
  1 | blafasel
(1 row)

test=*# with ok as (select * from chary where val = 'blafasel'), neu as (insert into chary (val) values ('blafasel') on conflict do nothing returning *) select * from ok union all select * from neu;
 key |  val   
-----+----------
  1 | blafasel
(1 row)

test=*# select * from chary;
 key |  val   
-----+----------
  1 | blafasel
(1 row)

test=*# with ok as (select * from chary where val = 'foobar'), neu as (insert into chary (val) values ('foobar') on conflict do nothing returning *) select * from ok union all select * from neu;
 key |  val   
-----+--------
  3 | foobar
(1 row)

test=*# with ok as (select * from chary where val = 'foobar'), neu as (insert into chary (val) values ('foobar') on conflict do nothing returning *) select * from ok union all select * from neu;
 key |  val   
-----+--------
  3 | foobar
(1 row)

test=*# select * from chary;
 key |  val   
-----+----------
  1 | blafasel
  3 | foobar
(2 rows)

test=*#

Leider kann MySQL dies nicht.
 
Werbung:
Das ist natürlich doof, dass MySQL dies nicht kann... Hatte die ganze Zeit eine Lösung nach dem Prinzip

Code:
SELECT
    id,
    IFNULL(id IS NULL, INSERT INTO test (name) VALUES('tet'); SELECT LAST_INSERT_ID())
FROM
    test
WHERE
    name = 'test';

gesucht, aber anscheinend ist MySQL wirklich zu doof :)
 
Zurück
Oben