My tables look like this:
Table "posts"
posts.id = PK, auto-increment
posts.text = varchar
posts.tag_id 1 = int, FK to tags.id
posts.tag_id 2 = int, FK to tags.id
posts.tag_id 3 = int, FK to tags.id
Table "tags"
tags.id = PK, auto-increment
tags.tag = varchar
Now I want to insert the following data:
text: 'lorem ipsum'
tag1: 'music'
tag2: 'pop'
tag3: 'singer'
So I need a query that checks if tag1/tag2/tag3 already exist in "tags", inserts them otherwise and then insert those as foreign-keys + the "text" into a new row in "posts".
I had a look into mysql INSERT IF NOT EXISTS but I'm just stuck and don't know where to start. I know I could handle it with multiple queries but there has to be another, lighter way to achieve the same result.
Has anyone any experience with this?
Update
A friend of mine proposed something like this:
CREATE FUNCTION getTagID(tag VARCHAR('100')) RETURNS int
INSERT INTO posts (text,tag1,tag2,tag3)
VALUES ('lorem ipsum', getTagID('music'), getTagID('pop'), getTagID('singer'));
Of course the implementation of getTagId is still missing, but does that make sense? getTagID should select the id with the given tag, if it doesn't exist, insert it and return this. Any help is appreciated.
Solution
I created a custom function in MySql:
DELIMITER ;;
CREATE FUNCTION getTagID(tag VARCHAR(100)) RETURNS BIGINT
BEGIN
DECLARE tagID BIGINT;
SET tagID = (SELECT id FROM tags WHERE text = tag);
IF tagID IS NULL
THEN
INSERT INTO tags (text) VALUES (tag);
SET tagID = (SELECT LAST_INSERT_ID());
END IF;
RETURN tagID;
END;;
DELIMITER ;
and now I can just insert into posts like that:
INSERT INTO posts (text,tag1,tag2,tag3)
VALUES ('lorem ipsum', getTagID('music'), getTagID('pop'), getTagID('singer'));
with that function, which inserts into "tags" only if the tag does not yet exist and gives back the ID of the existing or newly created tag. Yipeee :)