Can't Constrain Both Junction Table Columns - mysql

I have a juction table that contains two foreign keys (from Profiles and Districts tables), with both columns as a composite primary key.
`profID` int(11) NOT NULL,
`distID` varchar(8) NOT NULL,
PRIMARY KEY (`profID`,`distID`)
I'd like to constrain both columns, but MySql throws an error:
#1050 - Table './database_name/z#002dprof#002ddist' already exists
In troubleshooting the problem, I've tried creating another duplicate junction table from scratch, but I get the same error. Oddly, MySQL will allow me to constrain one column or the other, but not both columns. I'm stumped, since I have other (non-junction) tables that have constraints on more than one foriegn key column.
By the way, I'm using phpMyAdmin, and all tables are InnoDB with utf-8.
Any help would be appreciated.
ADDED: SHOW CREATE TABLE results
CREATE TABLE `Profiles` (
`profID` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(64) NOT NULL,
`stID` varchar(2) NOT NULL,
`zip` varchar(5) NOT NULL,
PRIMARY KEY (`profID`),
KEY `stID` (`stID`,`zip`),
KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8
CREATE TABLE `Districts` (
`distID` varchar(8) NOT NULL,
`stID` varchar(2) NOT NULL,
`abbrev` varchar(16) NOT NULL,
PRIMARY KEY (`distID`),
KEY `stID` (`stID`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `z-prof-dist` (
`profID` int(11) NOT NULL,
`distID` varchar(8) NOT NULL,
PRIMARY KEY (`profID`,`distID`),
KEY `distID` (`distID`),
KEY `profID` (`profID`),
CONSTRAINT `z-prof-dist_ibfk_1` FOREIGN KEY (`distID`) REFERENCES `Districts` (`distID`)
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I think I found a fix. Rather than using the phpMyAdmin function for adding a constraint (where I kept getting the error message), I instead followed marekful's lead by using an SQL ALTER TABLE query (with a new constraint name) as such:
ALTER TABLE `z-prof-dist`
ADD CONSTRAINT `test1`
FOREIGN KEY (`profID`) REFERENCES `Profiles` (`profID`)
ON UPDATE CASCADE
I still don't understand the cause of the original error, but I can see that the newly added foreign key constraint is working perfectly.

Related

I am trying to add foreign key constraint and am unable to figure out why it isn't adding the constraint [duplicate]

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.
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);
if you are giving
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so med_id should have primary key in medication or reference the columns of a UNIQUE constraint

How to make working: FOREIGN KEY error during addition

I have two tables, books and borrowing requests - I am making a study project to learn MySQL. Trying to link these two tables using a FK, and constantly get an error:
"SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
Apart from documentation, I searched virtually all of the related topics here on SO, however, no success. Types are the same, columns both unsigned, one primary key, etc. - to my understanding I have respected all of the provisions. But it does not work! What am I missing?
Here are the two tables and the fk addition query:
CREATE TABLE `books` (
`book_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`book_title` VARCHAR(100) NOT NULL,
`author_id` INT(11) NOT NULL,
`book_condition` INT(5) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `borrowing_requests` (
`request_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` INT(11) NOT NULL,
`book_id` INT(11) UNSIGNED NOT NULL,
`due_date` VARCHAR(55) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
FK Query:
ALTER TABLE `books` ADD CONSTRAINT books_fk FOREIGN KEY (`book_id`)
REFERENCES `borrowing_requests`(`book_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
You have the foreign key "backwards" - the borrowing request should reference a book, not the other way round:
ALTER TABLE `borrowing_requests` ADD CONSTRAINT books_fk FOREIGN KEY (`book_id`)
REFERENCES `books`(`book_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION

Unable to create foreign key in database

I am trying to create a table with a varchar column as foreign key but MySQL gives me an error while creating the table. My query is like this:
CREATE TABLE `survey_hesco_subdivision` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`circle_code` VARCHAR(100) DEFAULT NULL,
`name` VARCHAR(100) DEFAULT NULL,
`circle_name` VARCHAR(100) DEFAULT NULL,
`division_code` VARCHAR(100) DEFAULT NULL,
`sub_div_code` VARCHAR(100) NOT NULL,
`division_name` VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (`id`,`sub_div_code`),
KEY `id` (`id`)
) ENGINE=INNODB AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;
The above table is already in used
Create table `accurate_mam`.`meter_ping`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`meter_id` int(11) NOT NULL,
`meter_msn` varchar(100),
`sub_div_code` varchar(100) NOT NULL,
`sub_div_name` varchar(100),
primary key (`id`),
constraint `FK_PING_METER_ID` foreign key (`meter_id`) references
`accurate_mam`.`meters`(`id`) on delete Cascade,
constraint `FK_PIN_SUB_DIV` foreign key (`sub_div_code`) references
`accurate_mam`.`survey_hesco_subdivision`(`sub_div_code`) on delete Cascade
) ENGINE=InnoDB charset=latin1 collate=latin1_swedish_ci
The error I am getting is
Error Number : 1005
Error Message: Can't create table accurate_mam.meter_ping (errno: 150 "Foreign key constraint is incorrectly formed")
I have already looked into this question
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.
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
So, just create a index like this, before creating child table :
CREATE INDEX `idx_survey_hesco_subdivision_sub_div_code` ON survey_hesco_subdivision(sub_div_code);
Although, It is not best practice to use non-unique column as reference columns in relationship. DELETE CASCADE will not behave properly in that case. I will suggest you create a unique key on sub_div_code of primary table as well.
For more details, refere to this
Source : Cannot add foreign key - StackOverflow
Have you already run CREATE TABLE meters? There error is caused by that table being missing. Let's see that CREATE.

Simple Relation between 2 tables

I have a problem here.
I cannot add this to my db because one table is dependent of another and vice-versa.
So I get
Cannot add foreign key constraint
on the first create table that I put
How can I add this 2 tables if they both have constraints??
-- User Roles
CREATE TABLE IF NOT EXISTS `user_roles` (
`user_role_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`role` varchar(45) NOT NULL,
PRIMARY KEY (`user_role_id`),
UNIQUE KEY `uni_username_role` (`role`,`username`),
UNIQUE KEY `ix_auth_username` (`username`,`role`),
KEY `fk_username_idx` (`username`),
CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
-- Users
CREATE TABLE IF NOT EXISTS `users` (
`username` varchar(45) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`hashedPassword` varchar(500) NOT NULL,
`enabled` tinyint(1) NOT NULL DEFAULT '1',
`image` mediumblob,
`team` int(11) DEFAULT NULL,
`userRole` int(11) DEFAULT NULL,
PRIMARY KEY (`username`),
KEY `fkteam_idx` (`team`),
KEY `fkrole_idx` (`userRole`),
CONSTRAINT `fkrole` FOREIGN KEY (`userRole`) REFERENCES `user_roles` (`user_role_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fkteam` FOREIGN KEY (`team`) REFERENCES `team` (`idteam`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
To do this, you'll need to use deferrable constraint checks, but unfortunately MySQL does not implement this standard SQL feature.
As far as I know, only Oracle and PostgreSQL support this feature (deferrable constraints). These constraints are checked at the end of the transaction, and not on every single row insertion. That would solve your problem.
Therefore, you have two options:
Switch to Oracle or PostgreSQL (unlikely, I guess) or,
Change your table definition to allow one of the foreign key constraints to accept null values.
In the second case, you would:
Insert in the table that allow null in the FK, getting the generated ID.
Insert in the other table using the ID. Then, get the second generated ID.
Update the null in first table using the second ID.
Commit.
That's it.

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.
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);
if you are giving
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so med_id should have primary key in medication or reference the columns of a UNIQUE constraint