<- home

-- -------------------------------------------------------------------
--  Intersection table demo - tested on Oracle 12c
--  S Binder 2017-03-05
-- -------------------------------------------------------------------

-- -------------------------------------------------------------------
--  create the parent tables and the intersection, including
--  all PKs and FKs
-- -------------------------------------------------------------------

drop table visitor cascade constraints;
drop table event cascade constraints;
drop table uniqueticket cascade constraints;

create table visitor (
  vid varchar2(1) primary key
);

create table event (
  eid number primary key
);

--
-- intersection table
-- using Oracle's inline FK syntax...
--

create table uniqueticket (
  vid varchar2(1) constraint fk1 references visitor(vid),
  eid number constraint fk2 references event(eid)
);

alter table uniqueticket
add constraint upk
primary key (vid, eid);

-- -------------------------------------------------------------------
--  populate the parent tables
--  chr(x) -> returns character based on x (ASCII)
-- -------------------------------------------------------------------

begin
  for i in 1 .. 26
  loop
    insert into visitor values (chr(i+64));
    insert into event values (i);
  end loop;
end;

-- -------------------------------------------------------------------
--  populate the intersection table:
--  use a cross join (cartesian product) for retrieving/generating
--  all possible combinations of vid and eid
-- -------------------------------------------------------------------

begin
  for rec in (
    select * from visitor, event
  )
  loop
    insert into uniqueticket values (rec.vid, rec.eid);
  end loop;
end;

Alternative code (principle: use SQL instead of PL/SQL whenever possible ... ):

insert into uniqueticket select * from visitor, event;

-- -------------------------------------------------------------------

    select distinct count(*) from uniqueticket; -- 676 rows!

--
--  Trying to insert any combination into uniqueticket FAILS now!
--  All possible combinations are already stored in the
--  intersection table (uniquetickets).
--

<- home