简体   繁体   中英

How to make sure that a foreign key is not set in another table in SQL?

I'm working with Oracle Database 12c Enterprise Edition.

I have three tables:

table producer (
  pid int primary key,
  name varchar2(50)
);

table movie (
  mid int primary key,
  pid varchar2(50),
  name varchar2(50)
);

table moviecoproducers (
  mid int,
  pid int
);

The pid in the movies table such as the pid and mid in the moviecoproducers table are referenced by an appropriate foreign key. In addition the combination of the mid and pid values in the moviecoproducers table is unique.

I now have to ensure that no producer is referenced as (main) producer in the movie table and as co-producer in the moviecoproducer intermediate table for the same movie. I created a trigger to do that but now I'm asking myself if there would be a more eazy solution (eg a check constraint) if I would redesign my table structure.

Do I only need a trigger because of a bad design because I have no idea how to do it in a different/better way.

Create a typical 3-table many-to-many structure.

table producer (
  pid int primary key,
  name varchar2(50)
);

table movie (
  mid int primary key,
  name varchar2(50)
);

table movieproducer (
  mid int,
  pid int,
  status varchar2(10)
)

status will hold " main " or " co " values.

Now you can manage your restrictions with table constraints and no triggers.

An added bonus: if at some time in the future you want to introduce something like " junior co-producers " you would not need to alter your schema.

This design is not fully normalized: lack of status table. See if you are interested in adding it in.

Okay not sure what the varchar pid represents.. so lets start with a slightly less confusing table structure...

table producer ( producer_id int primary key,
                 producer_name varchar2(50) )

table movie ( movie_id int primary key,
              movie_data varchar2(50)
              movie_name varchar2(50) )

table movieproducers ( movie_id int*#
                       producer_type int*
                       producer_id int# )

Here we have 2 shared keys (or unique indexes) within MovieProducers. First the movie_id and producer_type where 1 would be the primary producer and any other number above 1 would be a co-producer preventing duplicating producer types -- and movie_id and producer_id which will eliminate a producer from appearing more than once for a specific movie)

I believe that would solve the issue you have and not require a trigger

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