我正在尝试向表中添加外键,但数据库 Sql Server 2005 不喜欢它。
它表示列与现有主键或唯一约束不匹配。
如何找到有问题的列以便删除/更改它们并添加外键?
最佳答案
在有问题的键上对父表进行左连接,然后检查左连接父表中值为空的子表中的值。
例如,如果这是您的模式...
table1:
myKey int primary key,
...other columns...
table2:
otherKey int primary key,
myKeyFromTable1 int
...other columns...
你会这样做:
select distinct
t2.myKeyFromTable1
from table2 t2
left join table1 t1 on t1.myKey = t2.myKeyFromTable1
where t1.myKey is null
这将为您提供 table2
中的不同值,这些值在 table1
中没有相应的父级。
关于sql - 查找与现有主键不匹配的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1178377/