开发者

Overriding unique indexed values

This is what I'开发者_如何学JAVAm doing right now (name is UNIQUE):

SELECT * FROM fruits WHERE name='apple';

Check if the query returned any result. If yes, don't do anything. If no, a new value has to be inserted:

INSERT INTO fruits (name) VALUES ('apple');

Instead of the above is it ok to insert the value into the table without checking if it already exists? If the name already exists in the table, an error will be thrown and if it doesn't, a new record will be inserted.

Right now I am having to insert 500 records in a for loop, which results in 1000 queries. Will it be ok to skip the "already-exists" check?


You can use the IGNORE feature:

INSERT IGNORE INTO fruits VALUES ('apple')

If there is a key violation, it just skips this value


check out

INSERT IGNORE INTO ...

and

INSERT ON DUPLICATE KEY UPDATE ...

Thes second method is preferred as the IGNORE statement simply causes mysql to issue warning instead of error

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜