簡體   English   中英

無法添加外鍵約束

[英]Cannot add foreign key constraint

我不知道這是怎么了。 我有很多表print, lamn, sec_lam, thi_lam, rewind, slit, ink和所有這些與job_code列相關的表,我正嘗試從order_basic添加每個表的外鍵,但是mysql給我Cannot add foreign key constraint錯誤。 還請建議我在每個表上索引哪一列。 這是我的表結構。

CREATE TABLE IF NOT EXISTS `dispatch` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` varchar(255) NOT NULL,
  `job_code` int(11) NOT NULL,
  `dispatch_qty` decimal(11,2) NOT NULL,
  `no_bags` int(11) NOT NULL,
  `no_pan` int(11)  NOT NULL,
  `no_roll` int(11) NOT NULL,
  `ch_no` int(11) DEFAULT NULL,
  `remarks` text NOT NULL,
  `prepaired` varchar(255) NOT NULL,
  PRIMARY KEY (`id`,`job_code`),
  FOREIGN KEY (`job_code`) REFERENCES order_basic(`job_code`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

這是我要外鍵形成此表的其他表

CREATE TABLE IF NOT EXISTS `order_basic` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `cd_date` varchar(25) DEFAULT NULL,
  `po_num` varchar(11) DEFAULT NULL,
  `po_date` varchar(11) DEFAULT NULL,
  `del_date` varchar(11) DEFAULT NULL,
  `job_code` int(11) NOT NULL,
  `job_name` varchar(255) NOT NULL,
  `customer_name` varchar(255) DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  `print_type` varchar(255) NOT NULL,
  `remarks` text,
  `prepaired` varchar(255) NOT NULL,
  PRIMARY KEY (`id`,'job_code')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

問題是您在order_basic上有一個復合主鍵:

PRIMARY KEY (`id`,'job_code')`

但您的外鍵僅引用job_code

FOREIGN KEY (`job_code`) REFERENCES order_basic(`job_code`)

由於job_code中不被限制為唯一, order_basic您不能在外鍵中引用它,因為同一代碼可以在order_basic引用多個記錄。

例如,在order_basic中,您可能具有:

id | job_code
---+---------
 1 |     1
 2 |     1
 3 |     1
 4 |     1

如果您在dispatch的job_code為1,那么這應該引用哪個記錄?

如果job_codejob_code是唯一的,則可以將其order_basic您的主鍵,或者在此列上添加唯一約束,以使您可以使用外鍵對其進行引用。 如果它不是唯一的,那么你不應該存儲job_code在調度,而是存儲相應的idorder_basic ,使這個您的外鍵。 如果您需要獲取特定調度記錄的job_code ,則可以使用order_basic.id列進行加入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM