MySQL – How to Get Same Value in Unique Column Differentiated by Other Column Values

indexMySQL

I have a table like this

 ID | PRODUCT_NAME | MANUFACTURER_ID | PACKAGE_ID
---------------------------------------------------
  1 |   VITAMIN A  |       1         |      1
  2 |  PARACETAMOL |       2         |      1

PRODUCT_NAME must be unique for same manufacturer and same package ID, BUT it can be duplicate if manufacturer ID or Product ID are different.
I tried using UNIQUE but it is rejecting same values with different Manufacturer ID or Package ID

My desired output would be like :

 ID | PRODUCT_NAME | MANUFACTURER_ID | PACKAGE_ID
---------------------------------------------------
  1 |   VITAMIN A  |       1         |      1
  2 |  PARACETAMOL |       2         |      1
  3 |   VITAMIN A  |       2         |      1

Notice third value of PRODUCT_NAME 'VITAMIN A' is same but MANUFACTURER_ID is different.
Do we have any work-around for this other than UNIQUE?

Best Answer

I think the problem here is that you were unaware that UNIQUE constraints can contain more than one field. Based on your question, I suggested 2 fields, i.e. both product and manufacturer.

It appears now (following comments) that 3 are required, as originally suggested by @ypercube.

From the link I originally posted here, the syntax you require is as follows:

CREATE UNIQUE INDEX 'my_product_uq'  
ON my_product (product_name, manufacturer_id , package_id);