I have a table as follows:
I would like to add a UNIQUE KEY
on (connection_id, parent_container_id, name)
. However, parent_container_id
and connection_id
are a disjoin union -- the record must have one or the other. Because of this, I thought perhaps using the value 1
as the 'null' value (that is, the first entry when using an auto-incrementing ID) and creating a BASE entry in the container
table for the 1
record.
Example data that I want to enforce uniqueness on:
(connection_id=1, parent_container=null, name="hello")
(connection_id=1, parent_container=null, name="hello") # should fail
(connection_id=null, parent_container=10, name="goodbye")
(connection_id=null, parent_container=10, name="goodbye") # should fail
Is this a poor approach to use or does this seem like a good way to enforce the Unique-ness constraint here? If it's not a good way, what might be a better way?
Update: my current solution is now using a generated (virtual) column with an md5 hash:
ALTER TABLE container ADD unique_hash2 CHAR(32) GENERATED ALWAYS AS
(MD5(CONCAT(COALESCE(connection_id, '-1'), COALESCE(parent_container_id, '-1'), name))) VIRTUAL UNIQUE