SQL主键的外键问题

时间:2012-05-30 21:44:20

标签: sql sql-server

我在 MSSQL Management studio上连接两个表时遇到问题。 我的目标是通过外键连接表,如果我删除用户,我想第二个表项将被自动删除。我计划使用DELETE Cascade方法。

User:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
[Email] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

电子邮件是主键

Payments:
 CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[Investor] [nvarchar](89) NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Investments] PRIMARY KEY CLUSTERED 
(
        [ID] ASC
 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,     ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

 GO

ID是主键

我的FK应该像USER-> PAYMENTS或PAYMENTS-> USER?

当我尝试连接用户时 - >通过电子邮件使用foregn密钥付款 - >投资者,它告诉我这样的错误:

  

表'付款'中的列与现有主键或UNIQUE约束不匹配。

你能解释一下我的问题在哪里吗?我做错了什么?

2 个答案:

答案 0 :(得分:3)

将您的结构更改为:

CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL);

ALTER TABLE [Users]
ADD CONSTRAINT PK_UsersID PRIMARY KEY (ID);

然后

CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[UserID] [bigint] NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL);

ALTER TABLE Investments
ADD CONSTRAINT PK_InstestmentsID PRIMARY KEY (ID);

ALTER TABLE Investments
ADD CONSTRAINT FK_UsersInvestments
FOREIGN KEY (UserID)
REFERENCES Users(ID);

然后在Users.ID

上加入Investments.UserID

答案 1 :(得分:2)

我搜索了您看到的错误消息(没有表名)和普遍的共识 似乎未在表格中正确设置PRIMARY KEYUNIQUE约束。该错误还告诉我您(可能)正在使用SQL Server。

来自technet.microsoft.com

  

外键关系的主键侧的列必须   参与主键或唯一约束。后   为其中一个表设置主键或唯一约束   您已经选择了,然后可以为此定义其他关系   表

检查两个表格中的PRIMARY KEYS。没有表格的实际DDL,很难获得更多帮助。

编辑Email表格中PRIMARY KEYUsers,但Email字段中未显示Investments字段1}}表。你在哪个领域加入了你的约束?