Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sql - MySQL error: Missing index for constraint

I am creating 2 tables in my database:

DROP TABLE IF EXISTS `med_pharmacy`;
CREATE TABLE IF NOT EXISTS `med_pharmacy` (
  `med_pharmacy_id` int(11) NOT NULL AUTO_INCREMENT,
  `med_id` int(11) NOT NULL,
  `med_barcode` varchar(45) DEFAULT NULL,
  `med_received` date DEFAULT NULL,
  `med_expiry` date DEFAULT NULL,
  `med_tablet` int(11) DEFAULT NULL,
  `med_pill` int(11) DEFAULT NULL,
  `clinic_id` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`med_pharmacy_id`),
  KEY `fk_med_pharmacy_medication1_idx` (`med_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1261 DEFAULT CHARSET=utf8mb4;

AND:

DROP TABLE IF EXISTS `medication`;

CREATE TABLE `medication` (
  `med_id` int(11) NOT NULL,
  `med_name` varchar(75) NOT NULL,
  `med_date_added` date DEFAULT NULL,
  `clinic_id` varchar(45) DEFAULT NULL,
  `med_type` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

And when I run the queries in wamp I got this error:

SQL query:

ALTER TABLE `med_pharmacy`   
ADD CONSTRAINT `fk_med_pharmacy_medication1` 
FOREIGN KEY (`med_id`) 
REFERENCES
`medication` (`med_id`) ON DELETE CASCADE ON UPDATE CASCADE MySQL

said: Documentation

#1822 - Failed to add the foreign key constaint. Missing index for constraint 'fk_med_pharmacy_medication1' in the referenced table 'medication'

The tables already exists but I changed one field.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The column referenced in a foreign key must be indexed. You need to add an index on medication.med_id. In fact, this should probably be the primary key of the table.

ALTER TABLE medication ADD PRIMARY KEY (med_id);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...