简体   繁体   中英

Cannot add foreign key constraint

I can not figure out What's wrong here.!! i have many table print, lamn, sec_lam, thi_lam, rewind, slit, ink and all of these table related by job_code column, i am trying to add foreign key each of these table from order_basic, but mysql give me Cannot add foreign key constraint error. and also please suggest me which column should index on each table. here is my table structure..

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 ;

Here is other table that i like to foreign key form this table

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 ;

The problem is that you have a composite primary key on order_basic :

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

but your foreign key only references job_code :

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

Since job_code is not constrained to be unique in order_basic you cannot reference it in a foreign key because the same code could reference more than one record in order_basic .

eg In order_basic you could feasibly have:

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

If you have a job_code of 1 in dispatch , which record is this supposed to reference?

If job_code is unique in order_basic then you can either just make this your primary key, or add a unique constraint on this column which will allow you to reference it with a foreign key. If it is not unique then you should not store job_code in dispatch, and instead store the corresponding id from order_basic and make this your foreign key. If you need to get the job_code for a specific dispatch record you can just join using the order_basic.id column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM