It is not letting me drop a foreign key - mysql

I am trying to remove a foreign key from a table but I am getting this error below in mysql:
1025 - Error on rename of './mobile_app/Question' to './mobile_app/#sql2-4517-15515' (errno: 152)
What does this error mean and how can it be fixed?
Below is the code where I am trying to drop the foreign key:
alter table Question drop foreign key FK_Option_Table;
Below is the Question Table details (no rows in this table):
CREATE TABLE `Question` (
`SessionId` varchar(10) NOT NULL DEFAULT '',
`QuestionId` int(5) NOT NULL,
`QuestionContent` varchar(5000) NOT NULL,
`NoofAnswers` int(2) NOT NULL,
`AnswerId` int(10) NOT NULL AUTO_INCREMENT,
`ReplyId` varchar(2) NOT NULL,
`QuestionMarks` int(4) NOT NULL,
`OptionId` varchar(3) NOT NULL,
PRIMARY KEY (`SessionId`,`QuestionId`),
KEY `FK_Option_Table` (`OptionId`),
KEY `FK_IndividualQuestion` (`QuestionId`),
KEY `FK_Reply` (`ReplyId`),
KEY `FK_AnswerId` (`AnswerId`)
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8
Below is the Option_Table details:
CREATE TABLE `Option_Table` (
`OptionId` varchar(3) NOT NULL,
`OptionType` varchar(20) NOT NULL,
PRIMARY KEY (`OptionId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
There are 24 rows in this table and below is a sample:
OptionId OptionType
O1 A-C
O2 A-D
O3 A-E
O4 A-F
...

Those are index's not foreign keys you have. I see no foreign keys in your create statements.
Example to create foreign key.
ALTER TABLE `Question`
ADD CONSTRAINT `SessionId`
FOREIGN KEY (`SessionId` )
REFERENCES `Option_Table` (`OptionId` )
ON DELETE NO ACTION
ON UPDATE CASCADE
, ADD INDEX `test_idx` (`SessionId` ASC) ;
ALTER TABLE `Question` DROP FOREIGN KEY `SessionId` ;

Related

I cant add MySQL foreign key constraint

I have three tables user, department, and department_hod
user has a department_id, which is the primary key of department, also departement has hod which is the primary key of user.
But i am getting an error when adding the foreign key constraint of username in department_hod table,
Please help
--
-- Create a user table
--
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` char(80) NOT NULL,
`emp_id` int(11) NOT NULL,
`designation` varchar(50) NOT NULL,
`department_id` int(11) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`email_id` varchar(50) NOT NULL,
`account_status` varchar(2) NOT NULL DEFAULT 'U',
`validity_date` TIMESTAMP,
`deactivation_date` TIMESTAMP ,
`deactivated_by` varchar(50),
`deactivation_remarks` varchar(1000),
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
CONSTRAINT `PK_USER_ID` PRIMARY KEY (`id`,`username`),
KEY `FK_DEPARTMENT_IDX_01` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_ID_01` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Create a department table
--
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Add department_hod table
--
CREATE TABLE `department_hod` (
`department_id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`username`,`department_id`),
KEY `FK_DEPARTMENT_idx_02` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_id_02` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS = 1;
error is here
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
Error is
Error Code: 1215. Cannot add foreign key constraint
Always provide complete error message. In a half of choices you may find the solution in it.
For your code the error message is
Failed to add the foreign key constraint. Missing index for constraint 'FK_USER_01' in the referenced table 'user'
So the problem can be fixed by absent index creation:
CREATE INDEX idx_user_username ON user (username);
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1f0fd24a8eb9cb5692b9d35dd1903045
can you please tell me that is it necessary to use index here? as it is only used for speeding up, do i have to use it beacuse of two primary keys in my user table? – shah-123
MySQL 8.0 Reference Manual / ... / FOREIGN KEY Constraints / Conditions and Restrictions
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

Why I am having a this error on phpmyadmin: Error creating foreign key on revision (check data types)?

I´m trying to create Foreign Keys in phpmyadmin, but I get this error:
Error creating foreign key on revision (check data types)
I don´t understand it because the data types are equal. So, what I want is to create a Foreign Key from 'acoustictreatment' to 'filterspecifications' which contains tag, offerid and revision. But I get the error that I mentioned.
This are my tables:
CREATE TABLE `offer` (
`projectid` varchar(20) NOT NULL,
`customer` varchar(255) NOT NULL,
`creator` varchar(255) NOT NULL,
`date` date NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `offer`
ADD PRIMARY KEY (`projectid`,`revision`);
CREATE TABLE `filterspecifications` (
`tag` varchar(100) NOT NULL,
`gasFlow` double NOT NULL,
`dustToHandle` double NOT NULL,
`offerid` varchar(20) NOT NULL,
`selectedFilter` varchar(20) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `filterspecifications`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`),
ADD KEY `offerid` (`offerid`,`revision`);
ALTER TABLE `filterspecifications`
ADD CONSTRAINT `filterspecifications_ibfk_1`
FOREIGN KEY (`offerid`,`revision`) REFERENCES `offer` (`projectid`, `revision`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE `acoustictreatment` (
`tag` varchar(100) NOT NULL,
`offerid` varchar(20) NOT NULL,
`outputFanSilencer` tinyint(1) NOT NULL,
`fanAcousticInsulation` tinyint(1) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `acoustictreatment`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`);
The solution that I found is to delete the 'acoustictreatment' table and create it again with the foreign key from the beginning. Because what I was trying to do was to create all the tables and then create the foreign keys, but that didn´t work for me

Cannot add foreign key constraint even with the same data type

| section | CREATE TABLE `section` (
`CourseNumber` varchar(10) NOT NULL,
`Quarter` varchar(10) NOT NULL,
`RoomNumber` varchar(4) DEFAULT NULL,
`DayTime` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CourseNumber`,`Quarter`),
CONSTRAINT `section_ibfk_1` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
| enrollment | CREATE TABLE `enrollment` (
`SSN` varchar(9) DEFAULT NULL,
`CourseNumber` varchar(4) DEFAULT NULL,
`Quarter` varchar(10) DEFAULT NULL,
`Grade` varchar(1) DEFAULT NULL,
KEY `SSN` (`SSN`),
KEY `CourseNumber` (`CourseNumber`),
CONSTRAINT `enrollment_ibfk_1` FOREIGN KEY (`SSN`) REFERENCES `Student` (`SSN`),
CONSTRAINT `enrollment_ibfk_2` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
mysql> alter table enrollment add foreign key(Quarter) references section(Quarter);
ERROR 1215 (HY000): Cannot add foreign key constraint
Column Quarter in both table Enrollment and Section have the datatype VARCHAR(10),so I am not sure what is causing the error.
If tables have data which do not respect foreign key you can not create it.
Try
SET foreign_key_checks = 0;
alter table enrollment add foreign key(Quarter) references section(Quarter);
SET foreign_key_checks = 1;
But i have used this to delete tables, do not know what will happen in this case.
This is a two fold problem...
Column Quarter is not already indexed in the target table enrollment.
Column Quarter is also not indexed in the source table section, although it is a part of the composite PRIMARY KEY along with CourseNumber.
So, if you just want Quarter from section table to be referenced in enrollment table, you'd need to:
ALTER TABLE `section` ADD INDEX( `Quarter`);
ALTER TABLE `enrollment` ADD INDEX( `Quarter`);
And thereafter:
ALTER TABLE enrollment ADD FOREIGN KEY(`Quarter`) REFERENCES section(`Quarter`);
However, if you want (CourseNumber, Quarter) as a composite foreign key, you would need to create a combined index on the two fields in enrollment table:
ALTER TABLE `enrollment` ADD INDEX( `CourseNumber`, `Quarter`);
And follow it up with:
ALTER TABLE `enrollment` ADD FOREIGN KEY( `CourseNumber`, `Quarter` )
REFERENCES section( `CourseNumber`, `Quarter` );
Must be some data preventing the creation as others have said. This worked fine when I ran it:
CREATE TABLE `Course` (
`CourseNumber` varchar(10) NOT NULL,
PRIMARY KEY (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `Student` (
`SSN` varchar(9) NOT NULL,
PRIMARY KEY (`SSN`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `section` (
`CourseNumber` varchar(10) NOT NULL,
`Quarter` varchar(10) NOT NULL,
`RoomNumber` varchar(4) DEFAULT NULL,
`DayTime` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CourseNumber`,`Quarter`),
CONSTRAINT `section_ibfk_1` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `enrollment` (
`SSN` varchar(9) DEFAULT NULL,
`CourseNumber` varchar(4) DEFAULT NULL,
`Quarter` varchar(10) DEFAULT NULL,
`Grade` varchar(1) DEFAULT NULL,
KEY `SSN` (`SSN`),
KEY `CourseNumber` (`CourseNumber`),
CONSTRAINT `enrollment_ibfk_1` FOREIGN KEY (`SSN`) REFERENCES `Student` (`SSN`),
CONSTRAINT `enrollment_ibfk_2` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Foreign key cannot be created id MySQL: missing index on column(s)

I have a few foreign keys set up, however phpMyAdmin would not let me to create one more. Here are table in question:
Groups Table
id
name
address
Tasks Table
id
group_id
name
I need a foreign key on group_id in Tasks Table, but when I try to create in it provides the following error: Missing index on column(s). If I add a unique constrain on group_id I am then able to create the foreign key, but the ralation then becomes One to One, which is not the expected result.
Following are table create statements:
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
`address` varchar(256) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
ALTER TABLE `groups`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`), ADD UNIQUE KEY `id_2` (`id`);
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
ALTER TABLE `fixed_tasks`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
Any help or guidance is much appreciated.
The following code can create two tables with relative foreign keys:
CREATE TABLE `Groups` (
`id` INT NOT NULL,
`name` VARCHAR(45) NULL,
`address` VARCHAR(45) NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `Tasks` (
`id` INT NOT NULL,
`group_id` INT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
CONSTRAINT `group_id`
FOREIGN KEY (`group_id`)
REFERENCES `Groups` (`id`)
);

Why can't I add a foreign key constraint this way?

Tables:
CREATE TABLE `relation` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`gender` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_relation` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `invite` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date_sent` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`relation_id` int(10) unsigned NOT NULL,
`email` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user` (`user_id`),
CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The SQL statement executed was:
ALTER TABLE `invite`
ADD CONSTRAINT `fk_relation`
FOREIGN KEY (`relation_id`)
REFERENCES `relation` (`id`)
ON DELETE CASCADE ON UPDATE RESTRICT
Mysql Error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'dbtest.#sql-d00_39' (errno: 121).
The relation.id and invite.relation_id columns are of the same type int(10) unsigned
UPDATE
The table invite is empty while adding this key.
The table relation has 3 rows.
try this :
ALTER TABLE invite
ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id)
REFERENCES relation(id)
According to the doc syntax is correct SQL FOREIGN KEY Constraint
The DDL for Foreign Key creation now automatically includes statements to specify actions on "Delete" and "Update". However, for "Delete", it includes the statement "ON DELETE RESTRICT", which does not appear to be a valid T-SQL statement.
TRY THIS :
ALTER TABLE invite WITH CHECK ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id) REFERENCES relation (id)