开发者

Adding a row with a certain value if it isn't in the table

I have a table setup with a UNIQUE column called, for example, test. I want to insert a row with the column test only if there isn't already a row in the table with test. I know I could just do the INSERT query and it would throw up an error if it already existed (and wouldn't really cause any harm AFAIK), but is there a way to do this properly using only MySQL? I'm pretty sure it can be done with functions but I've never us开发者_C百科ed those before and I think there's an easier way.


Sounds like a job for INSERT IGNORE:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.


Something like this should work

INSERT INTO TABLE(column1,column2)
SELECT value1, value2
WHERE 1 NOT IN (SELECT 1 FROM TABLE WHERE test='test')


You can use the IGNORE keyword, like this:

INSERT IGNORE INTO table_name (test) VALUES('my_value');

From the MySQL documentation:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

If you want to update the existing row rather than ignore the duplicate update entirely, check out the ON DUPLICATE KEY UPDATE syntax.


INSERT IGNORE (v,b,g) VALUES(1.2.3) will do nothing if you hit keys (primary or unique) but you should know your keys then. or just as John said, with preselcted data

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜