Let's say I have a table of products (product
) and a table of categories (category
) and between them there is a many-to-many relationship via a supplementary table (product_category_xref
).
Is there a way to make one, and only one category "primary"?
So far I have two ideas:
Create a separate column in the
product
table,primary_category
, and have it contain a key for the primary category. What I don't like about this is that either there will be redundancy in data (same category defined in bothprimary_category
andproduct_category_xref
) or category matching (verify vs.primary_category
and vs.product_category_xref.category
).Create
is_primary
, a boolean column inproduct_category_xref
. What I don't like about this, is that potentially there's a way to make several categories primary.
Also, integrity of a many-to-many relationship is enforced with foreign key, but I have no idea how to enforce only one primary category (or, perhaps, when a category is made primary, make all other categories of the same product non-primary).
What's the best way to do this?
UPDATE: The DBMS is MySQL interfaced via mysqli in PHP.
UPDATE2: Here's what I ended up doing.
I added a non-nullable integer column in the product_category_xref
table, priority
. The primary category is then where primary
is maximum. As a useful side effect, I can also sort categories.
I also added the same thing the other way around to allow sorting the products within a category.
Sure, this makes it harder to update the data, but that doesn't happen so often.