SQLite:确保一个条目小于另一条目作为约束
我想知道如何解决这个问题。
我有两个表
Table1 (t1_prim, t1_int) 以 t1_prim 作为主键,t1_int 不为空。
表2(t2_prim1、t2prim2、t2_int) 以 t2_prim1 和 t2_prim2 作为主键和外键约束 t2_prim1 引用 t1_prim。
如何定义一个约束来确保没有人在 t2_int 中输入大于 t1_int 中相应条目的整数?
我这样尝试(不起作用,因为你无法在检查约束中输入子查询):
CREATE TABLE table2
(t2_prim1 TEXT,
t2_prim2 INTEGER,
t2_int INTEGER NOT NULL,
PRIMARY KEY (t2_prim1, t2_prim2),
FOREIGN KEY (t2_prim1) REFERENCES table1(t1_prim),
CHECK (t2_int2 <= (SELECT t1_int2 FROM table1 WHERE t1_int1=t2_int1)));
而且我认为如果它像这样工作,还会有另一个问题。在更改 t1_int 时,如何检查该约束是否仍然满足?
I wonder how to solve this problem.
I got two tables
Table1 (t1_prim, t1_int)
with t1_prim as primary key and t1_int not null.
Table2 (t2_prim1, t2prim2, t2_int)
with t2_prim1 and t2_prim2 as primary key and foreign key constraint t2_prim1 references t1_prim.
how can I define a constraint that makes sure, that nobody enters an integer in t2_int that is bigger than the corresponding entry in t1_int?
I tried it like this (doesn't work because you can't enter subqueries in check constraint):
CREATE TABLE table2
(t2_prim1 TEXT,
t2_prim2 INTEGER,
t2_int INTEGER NOT NULL,
PRIMARY KEY (t2_prim1, t2_prim2),
FOREIGN KEY (t2_prim1) REFERENCES table1(t1_prim),
CHECK (t2_int2 <= (SELECT t1_int2 FROM table1 WHERE t1_int1=t2_int1)));
And I think there would be another problem if it would work like this. How do I check, that this constraint is still fullfilled when changing t1_int?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
终于找到了我的问题的答案。您可以通过使用触发器来解决问题。这是一个工作示例:
创建用于更新和插入的触发器:
如果您现在有以下表:
table1
table2
您将得到以下输出:
错误:输入小于所有的最大值数据库中 t2_int 的值!
错误:输入的值小于数据库中 t2_int 所有值的最大值!
错误:输入的值大于 t1_int 中的值!
错误:输入的值大于 t1_int 中的值!
错误:输入的值大于 t1_int 中的值!
虽然这些工作得很好:
Finally found an answer to my question. You can solve the problem by using triggers. Here's a working example:
Creating the triggers for updating and inserting:
If you have now the following tables:
table1
table2
You get this output:
Error: Input smaller than maximum of all values for t2_int in database!
Error: Input smaller than maximum of all values for t2_int in database!
Error: Input bigger than value in t1_int!
Error: Input bigger than value in t1_int!
Error: Input bigger than value in t1_int!
While those work perfectly well: