I’ve got a MySQL table with, among other things, two fields: a (int) and b (string) using the InnoDB engine.
I want to structure it so that a particular value of b can appear an arbitrary number of times in the table but every time it appears it must always appear with the same value of a, i.e. suppose my table looks like this:
(a,b)
(1,'foo')
(2,'bar')
(2,'bar')
(2,'baz')
I should be able to successfully insert (1,’foo’), (2,’bar’) or even (2,’qux’) into the table, but inserts of (2,’foo’), (1,’bar’) or (1,’baz’) should fail because whenever those string values of b appear they should always appear with the same value of a.
Any ideas how to do this efficiently? I’ve been playing around with transactions and SELECT ... FOR UPDATE but no luck. Do I have the wrong table structure?
I ended up using a statement like:
Which will only insert a row if the nested select returns no rows.