2011-09-25 58 views
0

我有一個使用MySQL 2005的數據庫。我有兩個表,Enrollment和AlertMsg。MySQL - 無法添加外鍵到表

註冊的主鍵是兩列,UnitCode和StudentID。這兩列都是另一個表的外鍵。

AlertMsg的主鍵是三列UnitCode,StudentID和AlertNo。

當我嘗試做與UnitCode外鍵在ALERTMSG表,就像這樣:

ALTER TABLE AlertMsg 
ADD FOREIGN KEY (UnitCode) 
REFERENCES Enrolment(UnitCode) 

我收到以下錯誤:

SQL Execution Error. 

Executed SQL statement: ALTER TABLE AlertMsg 

ADD FOREIGN KEY (UnitCode) 
REFERENCES Enrolment (UnitCode) 
Error Source: .Net SqlClient Data Provider 
Error Message: There are no primary or candidate keys in the referenced table 'Enrolment' that match the referencing column list in the foreign key 'FK_AlertMsg_UnitCo_571DF1D5'. 
Could not create constraint. See previous errors. 

經過一番搜索,似乎這是因爲UnitCode不是註冊的主鍵。但Enrollment的表格定義似乎表明它是。我在SQL方面有點新手,所以我假設如果表定義的最左邊的列中有一個鍵,就意味着它是表的主鍵。

誰能幫助?提前致謝。

+0

MySQL的2005? SQL Server 2005? – llazzaro

回答

1

The primary keys for enrolment are two columns, UnitCode and StudentID. Both these two columns are foreign keys to another table.

The primary keys for AlertMsg are three columns, UnitCode, StudentID and AlertNo.

你說「主鍵......」。實際上,它可能不是多個鍵,而是使用多個列創建的一個鍵。這些列一起是表中唯一需要的內容,因此不能只引用外鍵中的某一列。

如果你想要這個說法在UnitCode工作

ALTER TABLE AlertMsg 
ADD FOREIGN KEY (UnitCode) 
REFERENCES Enrolment(UnitCode) 

值表Enrolment需求是唯一的,您需要在該列中添加唯一約束。我想不是這樣,所以你不能添加必要的唯一約束。

你應該使用這個代替:

ALTER TABLE AlertMsg 
ADD FOREIGN KEY (UnitCode, StudentID) 
REFERENCES Enrolment(UnitCode, StudentID) 
0

標準主鍵不一定是表中最左邊的索引列,這只是開發人員和DBA定義表首先放置主鍵列的常見習慣。

在標準SQL,外鍵必須引用:

  • 柱(S)定義爲在參考表中的PRIMARY KEYUNIQUE KEY
  • 外鍵中的列不必具有相同的名稱,但它們在數量,順序和數據類型中必須相同。

我懷疑你真的使用Microsoft SQL Server 2005,而不是MySQL。沒有這種產品發佈被稱爲「MySQL 2005」。

0

你可以試試:

  • 添加外鍵約束報名表第2列(UnitCode,StudentID)。 或
  • 如果您只需要UnitCode列上的引用,則向Enrollment表的列(UnitCode)添加唯一約束。

Hth。