I have a very simple problem and a solution that will work, but I'm looking for a simpler one.
I'd like to prevent rows from being added to a database when multiple values equal existing values. For example, if a2=a1 AND b2=b1 then the data gets rejected. If only a2=a1 or only b2=b1 it is allowed. Basically I want it to act like a primary key that requires both values to match.
I know I can do this through validation before I write to the database--ex. select * where a='a2' and b='b2' and then avoid writing new data when I get results. What I'd rather do is enable a MySQL setting, like primary key, that will block data like this automatically.
I'm not very familiar with MySQL outside of basic features, so apologies if this is trivially easy. Googling for all sorts of things around unique index and primary key did not help.
Create a unique index for the columns that you want to be unique.
Eg:
CREATE UNIQUE INDEX index_name ON table(col1, col2);
See the MySQL Create index manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With