MySQL Adding Foreign Key - mysql

I have two tables:
Table 1: staff_incharge with following columns - First_name and staff_id (This is the Primary Key)
Table 2: student-info with following columns - First_name Last_name ID(Primary Key)
I have another column staff_id which I'm trying to make as a Foreign key, but it shows some error.
This is the query I'm using in MySQL Query Browser:
alter table `student_info`
add constraint foreign key (staff_id)
references staff_incharge(staff_id);
The error is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'student_info add constraint foreign key (staff_id) references
staff_incharge' at line 1.
Can someone tell me what I'm doing wrong?
student_info table was created first and then staff_incharge was created next.
Output of the following query:
SHOW CREATE TABLE student_info;
CREATE TABLE `student_info` (
`First_name` varchar(15) NOT NULL DEFAULT '',
`Last_name` varchar(45) NOT NULL,
`ID` int(10) unsigned NOT NULL DEFAULT '0',
`staff_id` int(11) NOT NULL DEFAULT '0',
`City` varchar(15) NOT NULL DEFAULT '',
`Marks1` int(10) unsigned NOT NULL DEFAULT '0',
`Marks2` int(10) unsigned NOT NULL DEFAULT '0',
`Marks3` int(10) unsigned NOT NULL DEFAULT '0',
`Total_marks` int(10) unsigned NOT NULL DEFAULT '0',
`Branch` varchar(10) NOT NULL,
PRIMARY KEY (`ID`,`First_name`)
SHOW CREATE TABLE staff_incharge;
'staff_incharge', 'CREATE TABLE `staff_incharge` (
`First_name` varchar(20) NOT NULL,
`Staff_id` int(11) NOT NULL,
PRIMARY KEY (`Staff_id`)
)

Minimum code - without explicitly naming the foreign key constraint (MySQL will choose a semi-random name):
ALTER TABLE student_info
ADD FOREIGN KEY (staff_id)
REFERENCES staff_incharge (staff_id) ;
Naming the foreign key constraint:
ALTER TABLE student_info
ADD CONSTRAINT staff_incharge__student_info__FK -- name of your choice
FOREIGN KEY (staff_id)
REFERENCES staff_incharge (staff_id) ;

I got it! The problem was that I had given different default values for ID and staff_id.
The main thing is to ensure foreign key and referenced column should have same data types, length, attributes, default values, collation.
These links helped:
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
http://forums.mysql.com/read.php?22,19755,499517

Related

Mysql Connot add foreign key constraint. how can I resolve it?

I tried to excute the query. but a error was occurred. the error message is 'Cannot add foreign key constraint'.
I supposed to create this table. but it didn't work.
CREATE TABLE IF NOT EXISTS `mydb`.`member` (
`idseq` INT(1) NOT NULL AUTO_INCREMENT,
`id` VARCHAR(50) NOT NULL,
`pw` VARCHAR(20) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`mobile0` VARCHAR(3) NOT NULL,
`mobile1` VARCHAR(3) NOT NULL,
`mobile2` VARCHAR(4) NOT NULL,
`mobile3` VARCHAR(4) NOT NULL,
`birth` DATE NOT NULL,
`admin_YN` VARCHAR(45) NOT NULL DEFAULT 'N',
`reg_date` DATE NOT NULL,
`upd_date` DATE NOT NULL,
PRIMARY KEY (`idseq`, `id`))
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `mydb`.`reservation` (
`reservation_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(50) NOT NULL,
`playMv_seq` INT(11) NOT NULL,
`reservaion_seat_code` VARCHAR(20) NOT NULL,
`reservaion_seat_num` INT(11) NOT NULL,
`reservation_charge` VARCHAR(20) NOT NULL,
`reservation_date` DATETIME NOT NULL,
PRIMARY KEY (`reservation_seq`, `user_id`, `playMv_seq`),
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 8
DEFAULT CHARACTER SET = utf8;
So I checked it detail from a query'show engine innodb status. the detail error message is
Error in foreign key constraint of table mydb/reservation:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
how can I resolve the error
You're trying to create a foreign key referencing the id column of the target table:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
But what is the actual key on that target table?:
PRIMARY KEY (`idseq`, `id`)
It's not id, if the composite of idseq and id. In order to reference that as a foreign key, you need local columns which match that:
`user_idseq` INT(1) NOT NULL,
`user_id` VARCHAR(50) NOT NULL,
And use both of them for the foreign key:
FOREIGN KEY (`user_idseq`, `user_id`)
REFERENCES `mydb`.`member` (`idseq`, `id`)
(Side Note: That primary key in member looks pretty strange to me in the first place. Why can't idseq by itself be the primary key? What is the purpose of id?)

cant create a MySql table

I have created this table
CREATE TABLE `Overview` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ops` varchar(11) NOT NULL,
`date` date NOT NULL,
`title` text,
`beneficiary_Institution` varchar(100) DEFAULT NULL,
`description` longtext,
`public_Expenditure_Budget` decimal(14,2) DEFAULT NULL,
`payments` decimal(14,2) DEFAULT NULL,
`completition_percent` int(11) DEFAULT NULL,
`start` varchar(11) DEFAULT NULL,
`finish` varchar(11) DEFAULT NULL,
`sub_projects` int(11) DEFAULT NULL,
`public_aid` decimal(14,2) DEFAULT NULL,
`operational_programme_number` int(11) DEFAULT NULL,
`operational_programme` varchar(100) DEFAULT NULL,
`title_ops` text,
`map_coordinates` varchar(15000) DEFAULT NULL,
PRIMARY KEY (`id`,`ops`,`date`)
)ENGINE=InnoDB;
and i try to create a table that has a foreign key with that
CREATE TABLE `Proposal_Body` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`ops` VARCHAR(11) NULL,
`title` VARCHAR(100) NULL,
`representative` VARCHAR(45) NULL,
`address` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_Proposal_Body_1_idx` (`ops` ASC),
CONSTRAINT `fk_Proposal_Body_1`
FOREIGN KEY (`ops`)
REFERENCES `espanew`.`Overview` (`ops`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)ENGINE=InnoDB;
This and any other attempt i tried gives me this error
ERROR 1005 (HY000): Can't create table
'Espa_Projects_Eng.Proposal_Body' (errno: 150)
I know that this is a foreign key problem, but i cant see the reason. This code is a comming from the mysql client, where i did the creation using the ui, didnt type the commands by hand, so it should work.
Thanks a lot
Reading from the documentation:
If you re-create a table that was dropped, it must have a definition
that conforms to the foreign key constraints referencing it. It must
have the correct column names and types, and it must have indexes on
the referenced keys, as stated earlier. If these are not satisfied,
MySQL returns Error 1005 and refers to Error 150 in the error message,
which means that a foreign key constraint was not correctly formed.
Similarly, if an ALTER TABLE fails due to Error 150, this means that a
foreign key definition would be incorrectly formed for the altered
table.
As you can see your first table has this primary key:
PRIMARY KEY (`id`,`ops`,`date`)
but in the second table the foreign key is:
FOREIGN KEY (`ops`)
You have to correct this to make it work.
Your Primary key is a composite key
PRIMARY KEY (id,ops,date)
And your foreign key is consist of only single column i.e.
FOREIGN KEY (ops)
Foreign keys have to match the primary/unique key they reference column for column. To remove this error either you need to add id and date to the Proposal_Body table or your first table Overview primary key is wrong and should just be (id).

#1215 - Cannot add foreign key constraint

I have this weird issue with creation of foreign key.
Given 2 tables:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) NOT NULL,
`merchant_id` int(11) NOT NULL,
`minimum_qty` int(11) NOT NULL,
`maximum_qty` int(11) NOT NULL,
`target_met_email` int(11) NOT NULL,
`coupon_barcode` text NOT NULL,
`coupon_merchant_address` int(11) NOT NULL,
`coupon_merchant_contact` int(11) NOT NULL,
`coupon_expiration_date` date DEFAULT NULL,
`coupon_price` int(11) NOT NULL,
`coupon_fine_print` int(11) NOT NULL,
`coupon_highlights` int(11) NOT NULL,
`coupon_merchant_description` int(11) NOT NULL,
`coupon_business_hours` int(11) NOT NULL,
`coupon_merchant_logo` int(11) NOT NULL,
`coupon_additional_info` text NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
`coupon_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`groupdeals_id` int(11) NOT NULL,
`order_item_id` int(11) NOT NULL,
`coupon_code` varchar(255) NOT NULL DEFAULT '',
`redeem` varchar(255) NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`coupon_id`),
KEY `fk_groupdeals_coupons_groupdeals1_idx` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I try to add foreign key by executing following query:
ALTER TABLE `groupdeals_coupons`
ADD CONSTRAINT `fk_groupdeals_coupons_groupdeals1`
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
All I receive is Error:
#1215 - Cannot add foreign key constraint
Show engine innodb status
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-17 13:47:49 7ff5dbb2c700 Error in foreign key constraint of table xxxxx/#sql-7b23_282b1a:
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
The column groupdeals.groupdeals_id is a primary one, so I really can't understand where is a problem :|
Any hints?
Server type: Percona Server
Server version: 5.6.11-rc60.3-log - Percona Server (GPL), Release 60.3
Your types are inconsistent:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
[...]
`groupdeals_id` int(11) NOT NULL,
As you will see, in one table you have int unsigned. In the other, just int.
BTW, I noticed you have two keys on groupdeals_id. Is that on purpose?
CREATE TABLE IF NOT EXISTS `groupdeals` (
[...]
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
Try these two steps to add foreign key:-
alter table groupdeals_coupons modify groupdeals_id int unsigned not null default 0;
ALTER TABLE groupdeals_coupons ADD CONSTRAINT fk_groupdeals_coupons_groupdeals1 FOREIGN KEY (groupdeals_id) references groupdeals (roupdeals_id);

It it possible to add a foreign key constraint to a composite key in mysql?

So I have 2 tables.
subject_schedule:
CREATE TABLE IF NOT EXISTS `subject_schedule` (
`subject` varchar(10) NOT NULL,
`schedule_id` int(11) NOT NULL,
`id` int(11) NOT NULL,
PRIMARY KEY (`subject`,`schedule_id`),
KEY `schedule_id` (`schedule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and appointment:
CREATE TABLE IF NOT EXISTS `appointment` (
`work_plan` varchar(1000) DEFAULT NULL,
`date` date DEFAULT NULL,
`homework_given` varchar(1000) DEFAULT NULL,
`tutor_comments` varchar(1000) DEFAULT NULL,
`admin_comments` varchar(1000) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`schedule_id` int(11) NOT NULL,
`attended` tinyint(1) NOT NULL DEFAULT '1',
`arrival_time` time DEFAULT NULL,
`departure_time` time DEFAULT NULL,
`homework_completed` tinyint(1) NOT NULL DEFAULT '0',
`subject` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `schedule_id` (`schedule_id`),
KEY `subject` (`subject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10004 ;
I want to create a foreign key which references the composite key in appointment. I have tried:
ALTER TABLE 'appointment'
ADD CONSTRAINT 'appointment_fk' FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES 'subject_schedule' ('schedule_id', 'subject');
but it returns an error in PhpMyAdmin:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near ''appointment' ADD CONSTRAINT 'appointment_fk' FOREIGN KEY
(schedule_id, `su' at line 1
What am I doing wrong?
Is it better to just have an id as a primary key and reference that instead of using a composite key?
the columnNames shouldn't be wrap with single quotes because it will be converted to a string (not a column anymore)
ALTER TABLE appointment
ADD CONSTRAINT appointment_fk FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES subject_schedule (schedule_id, subject);
SQLFiddle Demo

Foreign key constraint is incorrectly formed?

I got this error when create table: Foreign key constraint is incorrectly formed?
create table comment(
Comment_ID int UNSIGNED AUTO_INCREMENT not null,
User_1 varchar(50) not null,
Note_ID int(11) UNSIGNED not null,
PRIMARY key(Comment_ID),
CONSTRAINT `fk_1` FOREIGN KEY (`User_1`) REFERENCES `user` (`Dev_ID`),
CONSTRAINT `fk_2` FOREIGN KEY (`User_2`) REFERENCES `user` (`Dev_ID`),
CONSTRAINT `fk_3` FOREIGN KEY (`Note_ID`) REFERENCES `note`(`Note_ID`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
it's OK when I remove fk_3.
This my note table
CREATE TABLE `note` (
`Dev_ID` varchar(50) NOT NULL,
`Note_ID` int(11) UNSIGNED NOT NULL,
`Title` varchar(200) NOT NULL,
`Time` datetime NOT NULL,
`Mood` int(11) NOT NULL,
`Body` varchar(3000) NOT NULL,
`Visible` tinyint(1) NOT NULL DEFAULT '1',
`Share` tinyint(1) NOT NULL DEFAULT '0',
`Update` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`Dev_ID`,`Note_ID`),
CONSTRAINT `fk_note_user` FOREIGN KEY (`Dev_ID`)
REFERENCES `user` (`Dev_ID`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Thanks for help!
That's because the primary key of the note table is (Dev_ID,Note_ID) but you are only referencing one of those columns (Note_ID) in your constraint.
A FK constraint must always consist of all PK columns.
Also make sure that both tables are innoDB.
In addition to the answers that have been given, you would also get this error if the field types did not match. For example, if you tried to create a foreign key constraint between a varchar field and an int field.
This problem occur because the column
`Note_ID` int(11) UNSIGNED NOT NULL
Is neither primary nor unique.
Just make it
`Note_ID` int(11) UNSIGNED NOT NULL UNIQUE
And it will work.
One more addition: charsets of the fields must match.
In the referenced table I had ascii as a default charset: DEFAULT CHARSET=ascii was reported by show create table. I tried to create the referencing table with DEFAULT CHARSET=utf and I got 'Foreign key constraint is incorrectly formed'.
After I changed this to DEFAULT CHARSET=ascii on the new table (the referencing one), it was created successfully.
Ensure the collation is the same on both fields. I had the same problem when one was latin-general-ci and the other was utf8_unicode_ci. Not sure why the collation changed on the one table but fixing this resolved the issue.