简体   繁体   English

在 sqlite3 中引用(外键)表的一列通过连接其他两个表中的两列

[英]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.我在 python 中使用 sqlite3。我有两个表,每个表中都有 id 列。 These id columns in the tables can have different values.表中的这些 id 列可以有不同的值。 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.我想创建一个包含列 id 的新表,它可以通过组合前两个表的 id 列中的值来仅包含值。 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.我还尝试从两个表创建连接视图,并尝试将第三个表与连接连接起来,但没有成功。

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:请参阅此链接,作者在 sqlite 开始强制执行外键之前几乎告诉您如何执行此操作:

http://www.sqlite.org/cvstrac/wiki?p=ForeignKeyTriggers 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`:例如,这将是受限表的 INSERT 触发器,其中受限表是foo ,参考表是bar1和 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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