简体   繁体   English

SQL表关系

[英]SQL Table Relations

We have lots of tables in MS SQL that created without table relations many years ago. 许多年前,我们在MS SQL中创建了许多没有表关系的表。 Now we are trying to create a relationship between these tables. 现在,我们正在尝试在这些表之间创建关系。 The problem is in many of these developers used fake ids in the tables. 问题在于许多这些开发人员在表中使用了伪造的ID。

For example: TABLE A, ID(primary key) -> TABLE B, AID needs to be relational. 例如:表A,ID(主键)->表B,AID必须是关系型的。 But developers used some fake ids like -1,-2 to solve some problems in their side. 但是开发人员使用了一些伪造的ID(例如-1,-2)来解决自己的问题。 And now when I try to create a relation between TABLE A, ID(primary key) -> TABLE B, AID, I am getting errors. 现在,当我尝试在表A,ID(主键)->表B,AID之间创建关系时,出现了错误。

TABLE A 表A

ID | NAME
1  | name01
2  | name02

TABLE B 表B

ID | NAME   | AID
1  | name01 | 1
2  | name02 | -1
3  | name03 | -2

Is there way to solve this problem and is it meaning full what developers did, they didn't use any relations in sql, they are controlling everything in code-behind. 有没有办法解决这个问题,这意味着开发人员做了很多事情,他们没有使用sql中的任何关系,他们正在控制代码背后的一切。

Thanks 谢谢

You need to add those to your reference table. 您需要将它们添加到参考表中。 Something like this: 像这样:

insert into a (id, name)
     select distinct aid, 'Automatically Generated'
     from b
     where not exists (select 1 from a where b.aid = a.id) and
           a.id is not null;

Then you can add the foreign key relationship: 然后,您可以添加外键关系:

alter table b add constraint fk_b_aid foreign key (aid) references a(id);

The general idea of referential integrity is exactly that you can't have invalid references. 引用完整性的一般思想就是您不能有无效的引用。

So the best course of action here would be to suck it up and manually clean it up. 因此,最好的做法是将其吸起并手动清理。 Create the missing entries in the other table, or delete the records. 在另一个表中创建丢失的条目,或删除记录。

You can also ignore checks on existing data. 您也可以忽略对现有数据的检查。 If you are using sql server management studio to create relations there is option to do that just like in this screen shot 如果您正在使用sql Server Management Studio创建关系,则可以选择执行此操作,如此屏幕快照中所示

在此处输入图片说明

Hope it helps 希望能帮助到你

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

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