Rohit Agrawal
Rohit Agrawal

Reputation: 345

In sqlite3 reference(foreign key) a column of a table by join of two columns in other two tables

I am using sqlite3 in python. I have two tables with id column in each. These id columns in the tables can have different values. I want to create a new table with column id which can contain only the values by combining the values from the id columns of first two tables. I am able to successfully create foreign key(link) with any one of the table but not with both. I also tried creating a join view from the two tables and tried linking the third table with the join, but didn't work.

Upvotes: 2

Views: 749

Answers (1)

user610650
user610650

Reputation:

You can use triggers to create the equivalent of a foreign key on the union of columns from two distinct tables. You'll need to create triggers for inserts and updates on the constrained table, and for updates and deletes on the reference tables. If I'm not missing anything, you'll need six triggers in total.

See this link where the author pretty much tells you how to do it as it was written before sqlite started to enforce foreign keys:

http://www.sqlite.org/cvstrac/wiki?p=ForeignKeyTriggers

For example, this would be the INSERT trigger for the constrained table where the constrained table is foo, and the reference tables are bar1 and bar2`:

pragma foreign_keys=on;

create table bar1 (id integer primary key);
create table bar2 (id integer primary key);

insert into bar1 values (1);
insert into bar1 values (2);
insert into bar2 values (2);
insert into bar2 values (3);

create table foo (id integer);

CREATE TRIGGER fk_insert_foo
BEFORE INSERT ON foo
    FOR EACH ROW 
    BEGIN
      SELECT RAISE(ROLLBACK, 'insert on table foo violates foo.id '
                             + 'constraint on union of bar1.id and bar2.id')
      WHERE NOT (EXISTS (SELECT * FROM bar1 WHERE bar1.id=NEW.id)
                 OR 
                 EXISTS (SELECT * FROM bar2 WHERE bar2.id=NEW.id));
    END;

insert into foo values (1);
insert into foo values (2);
insert into foo values (3);
select * from foo;
insert into foo values (4); # <<<<<< this fails

Upvotes: 1

Related Questions