tags:

views:

29

answers:

2

Is there a way to make this statement into one? The basic idea is to insert a tag name if it doesnt exist and to retrieve the primary key for my next statement. title column is unique.

INSERT INTO `tag_name` (`count`, `title`) 
SELECT 0, @title FROM DUAL 
WHERE not exists 
    (SELECT * FROM `tag_name` WHERE `title` = @title LIMIT 1);

If rows affect >0 then use last_insert_rowid(), otherwise run this statement

SELECT id from  FROM `tag_name` WHERE `title` = @title

--- here is a test

CREATE TABLE test (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, data int unique);
//insert into test(data) select 5;
A: 

you can use the MySql specific Replace syntax. Check here for more information.

Faisal Feroz
I cant use replace. `REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted` from your link http://dev.mysql.com/doc/refman/5.0/en/replace.html
acidzombie24
If i used it then everytime i insert a tag i would have to update every column that is using the old id to the new id which could be expensive.
acidzombie24
A: 

you can use

insert into ... on duplicate update

this is insert row and when key was duplicate then update it.also u can use insert into on duplicate update field1=field1 this ignore on duplicate !

abdollah nouri
if it updates is LAST_INSERT_ID() set? i tried the syntax it doesnt work.
acidzombie24