5

I'm trying to create a constraint on table A to check if a set of records exists in a table B. I could use a foreign key, but the problem is that the data in the table B is non-unique.

Is there a way to create such a constraint without creating a trigger?

Edit: I can't change table B structure.

André Wagner
  • 1,330
  • 15
  • 26

3 Answers3

6

Foreign keys are a 1:N relationship. There can only be one parent record at the referenced end of the constraint. That's why we can only build foreign key constraints which reference unique keys.

You appear to be want a constraint which is M:N. This does not fit in a relational model. Perhaps what you need is a intersection table (AB) which links many records in table A with many records in table B? In fact, there may be several different modelling solutions, depending on your actual requirements.

Triggers won't work, partly because they won't scale but mainly because they won't work in a multi-user environment.

gouessej
  • 3,640
  • 3
  • 33
  • 67
APC
  • 144,005
  • 19
  • 170
  • 281
  • Thank you for you reply. I added a comment explaning that I can't change table B structure. – André Wagner Nov 05 '12 at 14:57
  • _”This does not fit in a relational model”_ - How so? Codd’s seminal paper alludes to the possibility of an RDBMS supporting arbitrary database-scoped constraints - it just wouldn’t be a _key_-constraint, but I believe it fits in the mathematical relational model just fine. – Dai Oct 15 '22 at 00:40
5

One technique would be to use a materialised view (fast refresh on commit) to store the unique values of the referenced column, and constrain your table against that.

Attempts at using triggers to enforce integrity are generally doomed due to read consistency or locking issues.

David Aldridge
  • 51,479
  • 8
  • 68
  • 96
0

I'm pretty sure the only way to enforce such a relationship is with a trigger.

As you mention, the data in table B is non-unique, so a foreign key will not work. (See also Can a foreign key reference a non-unique index?)

Check constraints come to mind, but they will not work here because:

  1. must not reference other tables
  2. cannot contain subqueries.

That being said, it may be possible that the reason the data in table B is not unique is that it is not normalized. It may be worth reviewing your schema to see if you can extract a unique relationship between A and B, possibly with the use of an intermediate table.

Community
  • 1
  • 1
lc.
  • 113,939
  • 20
  • 158
  • 187