3

I have the following tables:

// Base Scans
CREATE TABLE `basescans` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100) NULL DEFAULT NULL,
    `status_id` INT(10) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    CONSTRAINT `status_id_fk` FOREIGN KEY (`status_id`) REFERENCES `statuses` (`id`) ON UPDATE CASCADE ON DELETE SET NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT
AUTO_INCREMENT=29

// Statuses
CREATE TABLE `statuses` (
    `id` INT(10) UNSIGNED NULL AUTO_INCREMENT,
    `name` VARCHAR(100) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=4

Trying to save the first table fails when I put in that foreign key constraint. Can't figure out why. Both of the columns referenced in the constraint have the same type, size, etc:

INT(10) UNSIGNED NULL

They only have a difference default value. One has a default value of NULL, the other is AUTO_INCREMENT. I didn't think that made a difference for foreign key constraints but I could be wrong.

Both tables are InnoDB and UFT8. What am I missing here?

UPDATED: My specific error:

/* SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (`db`.<result 2 when explaining filename '#sql-31c2_22ac1e1'>, CONSTRAINT `status_id_fk` FOREIGN KEY (`status_id`) REFERENCES `statuses` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) */

2 Answers 2

6

You need to have already declared the table that the foreign key references, before you can define a foreign key that references it.

Once you declare the second table, you can then declare the first table. Tested here on MySQL 5.5.27.

If you need to bypass the validation, you can do this:

SET FOREIGN_KEY_CHECKS = 0;
-- declare tables
SET FOREIGN_KEY_CHECKS = 1;

http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_foreign_key_checks

3
  • Both tables already exist. The above code is the create table code. I'm just trying to add the foreign key. Oct 8, 2012 at 2:44
  • Are there any null values in statuses.id? Are there any values in basescans.status_id that don't exist in statuses.id? Oct 8, 2012 at 2:53
  • Ah that was the problem. I guess now that I read the error message about failing on a child row instead of the actual constraint relationship itself, it makes sense. Thanks! Oct 8, 2012 at 3:11
-2

Using query 1 and 2 for drop your table

1) SET FOREIGN_KEY_CHECKS = 0;

2) DROP TABLE TableName;

Here the TableName, which table you want to drop

3
  • 6
    Who said anything about dropping a table? Jun 12, 2014 at 7:02
  • Sorry,But this answer is usefull for some users. Jun 18, 2014 at 6:55
  • I mean, it doesn't look that way...
    – Rambatino
    Jul 29, 2020 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.