I have a MySql table, with field1(id), field2(name) and field3(surname).
Id like to insert the value only if the pair field2 and field3 are not already insered. How can I do it?
INSERT IGNORE doesnt work because the field1 is int autoincrement and every INSERT is different.
P.S. I'd like to get rid about REPLACE INTO, because it doesnt make sense "rewrite" data if it already exist
Cheers
EDIT
Table structure id = INT primary name = VARCHAR surname = VARCHAR
name and surname can't be each UNIQUE (i can have 2 name or surname with the same va开发者_开发知识库lues). What i want is that the pair name and surname haven't the same value.
es :
0 Marco Cordi (OK)
1 Marco Daghine (OK)
2 Fabio Cordi (OK)
3 Marco Cordi (NOT OK, is already definied)
For someone to answer this question for you, you need to post your actual table structure (including any primary/unique keys that exist).
If your table has no primary/unique keys, then the only way to do this is to run a SELECT and see if you get any rows back, and perform the INSERT if there are no rows found.
If you want the rows in your table to be unique on field2 and field3, then you should create a unique index on those columns (which can be done with the ALTER TABLE query).
EDIT: you want a unique index, not on each of those fields individually, but on BOTH of them. You want to run this query:
ALTER TABLE `yourtable`
ADD UNIQUE INDEX `unique_name` (`field2`, `field3`);
Once you have done that, you can use INSERT IGNORE.
update myTable
set name = coalesce(name, 'newname'),
surname = coalesce(surname, 'newsurname')
where id = myID;
(Updated)
insert into myTable(name, surname)
values ('newname', 'newsurname')
where NOT EXISTS (select id from myTable where name = newname and surname = surname) ;
精彩评论