开发者

mysql conditional insert

开发者 https://www.devze.com 2023-02-12 16:55 出处:网络
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);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消