4

我有一个表 X,它有一个自动递增的 ID 列作为它的主键。我还有其他表 A、B、C 和 D 来补充表 X 中的信息。每个表都必须包含一个引用表 X 中 ID 的列。我已经做到了,并且在我的代码(Java)中我有一个将每个条目的 ID 返回到表 X 并在插入其他表时使用它的方法。一切运作良好。

现在,有人建议我将表 A、B、C 和 D 上的那些 ID 列分配为 FOREIGN KEYS,因为“这是正确的做法”。我这样做了。现在从表 X 中删除行需要花费大量时间才能完成。插入其他表也需要更长的时间。

请不要误会我的意思,我知道为什么外键与指定数据库上的表关系有关。但它开始看起来只是仪式性的,而不是实际相关的,尤其是当我的交易变得越来越慢时。

问题:

1. 为了保持官方规定的关系而失去一些表现是否值得,即使这不是必要的?

2. 有什么方法可以加快我的交易速度,同时保持 FOREIGN KEY 规范。

谢谢。

回复

以下是表的创建方式。

创建表 SQL:

CREATE TABLE [dbo].[MainTableX](
    [col1] [smalldatetime] ,
    [col2] [varchar] (20) ,
    [ID] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_MainTableX] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)
)
GO


CREATE TABLE [dbo].[RelatedTableA](
    [differentID] [varchar] (50),
    [detail1] [varchar] (40),
    [detail2] [varchar] (40),
 CONSTRAINT [PK_RelatedTableA] PRIMARY KEY CLUSTERED 
(
    [differentID] ASC
)
GO

-- Tables B, C D are pretty much similar to table A

添加外键 SQL:

ALTER TABLE RelatedTableA ADD ID INT 
CONSTRAINT fk_refTableX_A FOREIGN KEY (ID)
REFERENCES MainTableX(ID) 
GO
-- Same thing with the other related tables

解决方案

我将外键列设为索引。现在我的查询又快了。

Create nonclustered index IX_RelatedTableA 
on RelatedTableA (ID) 
GO
4

2 回答 2

5

如果 FOREIGN KEY 列被正确索引(我相信这应该随着声明自动发生),那么你应该看到最坏的性能损失。请列出每个表的 CREATE TABLE SQL,因为这听起来好像有问题。

SQL Server 不会自动在 FK 列上创建索引,因此请确保您自己执行此操作。

使用 FOREIGN KEY 关系的目的不是“正式声明”任何事情(或者在任何情况下都不仅仅是这样做)。相反,它为数据库引擎提供了足够的信息来强制执行数据的完整性。这意味着您不能错误地让您的应用程序添加或删除记录,从而违反关系。此外,使用该数据库的其他应用程序(例如 Management Studio)也无法做到这一点。正是由于这个原因——通过数据库引擎保证规则的执行——声明约束很重要。

于 2013-08-28T20:07:28.303 回答
1

The foreign keys are not your problem. And you do not want to remove them. When you delete a row from table X, I assume you are first deleting rows from tables A, B, C and D first? You would have to if you have FK's established. How are you removing the rows from these tables? From within your Java application? If so, it would be significantly faster to set up your FK's to do a cascading delete. That way, you can make a single call to delete the row in table X and all the child rows get deleted automatically by SQL Server. You would save yourself four trips to the DB for each deletion from table X.

BTW, there is more value ot FK's than just maintaining data integrity (which is huge). If you intend to ever start using an ORM (e.g., Entity Framework), having FK's in place will make your life much easier.

于 2013-08-28T20:23:22.003 回答