如何查询与约束不匹配的外键?
SQL Server 2005。
我正在将外键约束添加到据称不需要它们的应用程序的数据库中。 当然,数据变得不可靠,并且外键字段中存在孤立条目。
设置:
两个表,TableUser 和 TableOrder。 TableUser 具有主键“UserID”,TableOrder 具有外键“UserID”。
如何查找 TableOrder.UserID 在 TableUser.UserID 中没有匹配条目的行?
例如,TableOrder.UserID 的值为 250,但没有与 250 匹配的 TableUser.UserID 键。
SQL Server 2005.
I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them. Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.
Setup:
Two tables, TableUser and TableOrder.
TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.
How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?
For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法:
有许多不同的方法可以编写此类查询。
Here's one way:
There are many different ways to write this sort of query.
另一种常见的方法是左外连接:
此查询在没有 where 子句的情况下也很有用,可以浏览并查看相应的值(如果存在),并查看哪些值不匹配。
The other common approach is a left-outer join:
This query can also be useful without the where clause, to browse through and see the corresponding values (if they exist), and see which ones have no match.
表中一开始就没有 FK 约束。 它们像 FK 和 PK 一样使用,但没有编码——人们认为它们是不必要的开销。 所以我们拥有所有列,但没有编码约束。 当我去落实的时候,我发现有很多违规的地方。
你的问题凸显了问题。 它们不是不必要的开销,它们可以防止人们遭受一般数据库破坏。
格雷格和布拉德的回答都帮助了我。
There were no FK Constraints in the tables to begin with. The were used like FK and PK but not coded -- the belief was that they were unnecessary overhead. So we have all the columns, but no coded constraints. When I went to put them in so that they would be enforced, I discovered that there were lots of violations.
Your question highlights the problem. They are not unnecessary overhead, they prevent people from general database asshattery.
Both Greg and Brad's answers helped me out.