mysql conditional insert
can we have sql insert like this?
INSERT INTO
A_has_B
(A_id
,B_id
) VALUES (1,2) IF NOT (SELECT COUNT(A_id
) FROM A_has_B
WHERE A_id
= 1 AND开发者_JS百科 B_id
= 2);
To answer your question, you could certainly do:
insert into A_has_B ( A_id, B_id )
select 1, 2
from A_has_B
where A_id = 1 and B_id = 2;
However, I think what you are looking for is insert ignore
:
insert ignore into A_has_B ( A_id, B_id ) values (1, 2);
This way you just ignore if there are duplicate rows and you have a proper primary key on the values.
精彩评论