Scenario : Multiple product images, one main image.
Currently, I’ve got 2 tables to manage this. One for storing product images and another table for storing mainProductImageIds. In the table that stores a list of mainProductImageIds, I’ve got a unique index on prodid+isMain to enforce One Main Image Per Product Id.
My Question relates to the table below (if I was going to only use 1 table). How would I enforce 1 isMain=1 per prod? Is there any index setting that would error when I tried to set isMain=1 to image_id=2 since image=1 is already the main image? You can’t put a unique_key on prod+isMain.
|image_id |prod|isMain
|---------|----|------
|0 |1 |0
|1 |1 |1
|2 |1 |0
|3 |2 |1
|4 |3 |0
|5 |3 |1
The answer, I learned, is really simple and has to do with how MySQL indexes NULL values. Over Here they talk about:
so as long as my
isMainfield allow enforces one value and NULL (maybe an ENUM), I’m all set. The unique_index will only be enforces when isMain is set to a distinct value and not when it is set to NULL.The Updated Table Looks like This: