简体   繁体   中英

Disabling single constraint in MySQL db without dropping it

I want to disable a single unique key constraint out of many without dropping it in MySQL db. Can someone please let me know.

There are two ways to answer this question.....

if your goal is to store data that's unique (except that one case, which is an exception), you're out of luck. A unique key constraint for a table is exactly that.... a unique key constraint for a table. And storing duplicate keys in a unique key column just isn't gonna work.

Now, if you're trying speed up data inserting because you already know your data are unique, that's a different matter. Under those circumstances, you can set unique_checks = 0, insert your data, then turn them back on again

This describes the process: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_unique_checks

Quoting from that:

If set to 1 (the default), uniqueness checks for secondary indexes in InnoDB tables are performed. If set to 0, storage engines are permitted to assume that duplicate keys are not present in input data. If you know for certain that your data does not contain uniqueness violations, you can set this to 0 to speed up large table imports to InnoDB.

Note that setting this variable to 0 does not require storage engines to ignore duplicate keys. An engine is still permitted to check for them and issue duplicate-key errors if it detects them.

In other words, you can tell your database to trust you that you're not inserting data with duplicate keys... it may still check anyway, and you certainly cannot store duplicate keys in the table while there's a unique key constraint. But you might be able to speed up inserts wit h this.

Btw, I am not aware of any way that you could disable unique key checks for a specific column, although I can't say for certain that it is impossible. That is, I am not aware of (and neither do I believe there is) any way to ignore checks for one specific column out of many... but I cannot say for certain that it's strictly speaking impossible.

Depending on what your actual needs are (beyond disabling the key without deleting it, but rather why you need to disable that key without deleting it), you might also be able to get away with using ON DUPLICATE KEY ( https://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html ). Alternatively INSERT IGNORE might accomplish what you want, but I'd be extremely careful with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM