简体   繁体   English

从同一表的两列到同一主键的外键

[英]Foreign keys from 2 columns of the same table to the same primary key

I have two tables: 我有两个表:

users 用户

id  |  username
--------------
 1  |  James
 2  |  John
 3  |  Jack
 4  |  Jim
 5  |  Jane
 6  |  Jessica

juniors 晚辈

senior_id  |  junior_id
-----------------------
 1         |  4
 1         |  6
 2         |  3
 4         |  5

Both the senior_id and junior_id refer to the users table's id column. senior_idjunior_id引用users表的id列。

How do I set it up so that a) it is guaranteed that both senior_id and junior_id exist in users and b) a delete from users will cascade and remove any instances of the deleted id from juniors whether it's a senior_id or junior_id ? 我该如何设定,让一个)可以保证两个senior_idjunior_id中存在users和b) deleteusers将级联和删除已删除ID的任何实例juniors是否是一个senior_idjunior_id Ie deleting Jim in the example above will automatically remove both the first and last record from juniors. 即,在上面的示例中删除Jim会自动从少年中删除第一个和最后一个记录。

I tried doing this with two separate constraints. 我尝试使用两个单独的约束来执行此操作。 But if I set up cascade on both constraints I get a 'may cause cycles or multiple cascade paths' error. 但是,如果我在两个约束上都设置级联,则会出现“可能导致循环或多个级联路径”错误。

And if I set it on only one constraint then a delete fails (in a case like Jim) because it cascades to only one of the columns and thus then violates the constraint. 如果我仅将其设置为一个约束,则删除操作将失败(在类似Jim的情况下),因为它仅级联到其中一列,因此违反了约束。

I have to be able to do this on SQL Server 2005. 我必须能够在SQL Server 2005上执行此操作。

Remove FK constraint.For FK constraint check.Create trigger on table juniors before insert/update.if id do not exists then rollback.Again now create another trigger on table User for DELETE.and in trigger write script to delete all record.since FK do not fulfill your requirement,therefore no point in keeping one extra constraint. 删除FK约束。进行FK约束检查。在插入/更新之前在表juniors上创建触发器。如果id不存在,则回滚。现在再次在表User上为DELETE创建另一个触发器。并在触发器写入脚本中删除所有记录。不能满足您的要求,因此毫无意义地保持一种额外的约束。

Most importantly I think your table design is bad.Table design should be like Employee-Manager relation table ie keep SeniorID in User Table itself. 最重要的是,我认为您的表设计不好。表设计应类似于Employee-Manager关系表,即将SeniorID保留在用户表中。

so many of your problem will vanish . 因此,您的许多问题都将消失。 Also there is no extra cost or complication for any query on this table 此外,此表上的任何查询都没有额外的成本或复杂性

id  |  username   SeniorID
--------------
 1  |  James
 2  |  John
 3  |  Jack        2
 4  |  Jim         5 
 5  |  Jane
 6  |  Jessica

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

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