简体   繁体   中英

How to model referential integrity for one-to-many relationship, where many > 0

I cannot figure out how to ensure data integrity on DB level in a case where I have a 1:N relationship, where N has to be at least one. Let me describe:

I have Datasets and Stored filters . Stored filters can be associated with/applied to more than one dataset, but always at least one. When the last associated dataset is removed, so should be the filter as to not have dangling filters. The inverse is not true (when a filter is removed, no changes to datasets). Is there a way to model this behavior in RDBMS like MySQL/MariaDB/PostgreSQL? Or am I destined to resolve this on the code level?

This is a tricky relationship to represent. The problem is probably more apparent in inserting rows:

  • You can't insert a filter until you have a dataset .
  • You can't insert a dataset until it has a filter .

My suggestion is that you manage this using an on delete trigger on datasets . If the last dataset for a filter is deleted, then delete the associated filter.

Or, just use a soft delete. Use a trigger to maintain a counter of the number of datasets on a filter. When the counter is 0 , then the filter is inactive.

From the other side - is immediate "filter without datasets" removing critical? maybe, simple event procedure which scans filters table and removes non-referential filters, with some period (for example each minute), is enough? – Akina

@Akina not critical just would require an additional check on the application code part to ensure that there is actually a dataset present. Right now it is treated as implicit truth. – Patrick Kusebauch

CREATE EVENT remove_dangling_filters
ON SCHEDULE EVERY 1 MINUTE
DO
DELETE FROM filters
WHERE NOT EXISTS ( SELECT NULL
                   FROM datasets
                   WHERE datasets.filter_id = filters.id );

If some filter have no related datasets (last related dataset removed) then this filter will be deleted within a minute.

Adjust deleting query according to real structures and relations. Add additional logic if needed (for example, copying the filter to archive table, writing log, etc.). Adjust execution schedule to safe period (not recommended to do it less than 5-10 second).

Created once. Application logic not needed.

Do not forget to enable Event Scheduler .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM