MySQL Not allowing delete even though FK relationship ON DELETE CASCADE set - mysql

I am working on a project that makes use of a MySQL Database to store snippets of code for use on multiple websites. For each content snippet I also keep an edit history table, to which I add a record every time a snippet is updated. Occasionally it will be desirable to delete a snippet completely, and any associated edit history. When setting up the DB, I set up the foreign key relationship to ON DELETE CASCADE so that deleting the snippet will automatically delete the history. However, I am getting the following error:
Error in query: delete from SNIPPET where id = 1. Cannot delete or update a parent row: a foreign key constraint fails (universal_content_repository/SNIPPET_EDIT_HISTORY, CONSTRAINT fk_SNIPPET_EDIT_HISTORYRelationship13 FOREIGN KEY (snippet_id) REFERENCES SNIPPET (id))
Here is the code I use to create the DB as well as the relationships:
/*Schema universal_content_repository*/
CREATE SCHEMA IF NOT EXISTS `universal_content_repository`
DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `universal_content_repository`;
CREATE TABLE `universal_content_repository`.`USER` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Stores the ID for the User.',
`username` VARCHAR(20) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`is_active` VARCHAR(5) NOT NULL DEFAULT true,
`password` VARCHAR(32) NOT NULL,
`is_admin` BIT NOT NULL DEFAULT 0,
`prefers_wysiwyg` BIT DEFAULT 0,
PRIMARY KEY (`id`)
) COMMENT 'Stores information about all Users for the Universal Content Repository.' ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SNIPPET` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`content` TEXT NOT NULL,
`created_by` INT UNSIGNED,
`wysiwyg_editable` VARCHAR(6) NOT NULL DEFAULT true,
`is_enabled` BIT NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
) COMMENT 'Guarantees that no two snippets may have the same name or ID.' ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`IMAGE` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL,
`url` TEXT NOT NULL,
`alt` VARCHAR(32),
PRIMARY KEY (`id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` (
`rel_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`snippet_id` INT UNSIGNED,
`image_id` INT UNSIGNED,
`position` INT COMMENT 'Stores the position of the image within the snippet, as notated in the snippet as [index]',
PRIMARY KEY (`rel_id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` (
`revision_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`editing_user` INT UNSIGNED,
`snippet_id` INT UNSIGNED,
`old_contents` TEXT NOT NULL COMMENT 'Stores the old contents of the snippet.',
`edit_date` DATETIME NOT NULL COMMENT 'Stores the DateTime of the edit.',
PRIMARY KEY (`revision_id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SESSION` (
`id` VARCHAR(32) NOT NULL COMMENT 'Stores the Session ID',
`access` INT(10) UNSIGNED NOT NULL,
`data` TEXT,
PRIMARY KEY (`id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
ALTER TABLE `universal_content_repository`.`USER` ADD UNIQUE `Identifiers` (`id`,`username`);
ALTER TABLE `universal_content_repository`.`SNIPPET` ADD UNIQUE `identifiers` (`title`,`id`);
ALTER TABLE `universal_content_repository`.`SNIPPET` ADD CONSTRAINT `fk_SNIPPETRelationship8` FOREIGN KEY (`created_by`) REFERENCES `universal_content_repository`.`USER`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` ADD CONSTRAINT `fk_IMAGE_IN_SNIPPETRelationship10` FOREIGN KEY (`snippet_id`) REFERENCES `universal_content_repository`.`SNIPPET`(`id`) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` ADD CONSTRAINT `fk_IMAGE_IN_SNIPPETRelationship11` FOREIGN KEY (`image_id`) REFERENCES `universal_content_repository`.`IMAGE`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` ADD CONSTRAINT `fk_SNIPPET_EDIT_HISTORYRelationship12` FOREIGN KEY (`editing_user`) REFERENCES `universal_content_repository`.`USER`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` ADD CONSTRAINT `fk_SNIPPET_EDIT_HISTORYRelationship13` FOREIGN KEY (`snippet_id`) REFERENCES `universal_content_repository`.`SNIPPET`(`id`) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
If you want to see a graphical representation of the DB, you can see it at SchemaBank.
For those without a SchemaBank account, here is the ER:
Any ideas?

Looks like your code is right.
If it's practical, dump that database and restore it onto a different server as a test. If INNODB and MySQL internal states have gotten out of sync, that should give you a well-behaved database on the server you restore to.

Related

How to add two foreign keys and add values in child table with reference of parent table

I have 3 tables in my database USERS, QUESTION, and ANSWER. I want QUESTION table to interact with USERS and ANSWER table and ANSWER table to USER and QUESTION table. So far I have related QUESTION table with USERS table using foreign key and ANSWER table with QUESTION table.
When I am trying to add second foreign key in ANSWER table in mysql I am getting an error
a) Duplicate foreign key constraint name 'userid'
Even if I am trying to add using query it still giving me an error.
Can I add values in QUESTION table in reference with USERS table with help of foreign key? for e.g. i have user in USERS table with userid 1 i want to add values in QUESTION table where quesid will be 1 and also userid also be 1. Till now I have tried this query
INSERT INTO users_ques
SELECT "What is JAVA","Please Share the details" FROM users WHERE quesid = 1;
Below are my tables and their script
USERS TABLE
CREATE TABLE `users` (
`userid` int NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`firstname` varchar(45) NOT NULL,
`lastname` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`phone` int DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
QUESTION TABLE
CREATE TABLE `users_ques` (
`quesid` int NOT NULL AUTO_INCREMENT,
`ques` varchar(50) NOT NULL,
`ques_desc` varchar(150) NOT NULL,
PRIMARY KEY (`quesid`),
CONSTRAINT `userid` FOREIGN KEY (`quesid`) REFERENCES `users` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
ANSWER TABLE
CREATE TABLE `users_ans` (
`ansid` int NOT NULL AUTO_INCREMENT,
`ans` varchar(200) NOT NULL,
PRIMARY KEY (`ansid`),
CONSTRAINT `quesid` FOREIGN KEY (`ansid`) REFERENCES `users_ques` (`quesid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Recommended structure (use as a base, adjust to real data):
CREATE TABLE user (
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
username VARCHAR(255) NOT NULL,
password VARBINARY(255) NOT NULL, -- password hash, binary
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) DEFAULT NULL,
email VARCHAR(255) DEFAULT NULL,
address VARCHAR(255) DEFAULT NULL,
phone BIGINT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE question (
question_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
question_text TEXT NOT NULL,
user_id INT NOT NULL, -- id of the user who have asked
CONSTRAINT user_to_question FOREIGN KEY (user_id) REFERENCES user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE answer (
answer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
answer_text TEXT NOT NULL,
question_id INT NOT NULL, -- what question it answers on
user_id INT NOT NULL, -- id of the user who have answered
CONSTRAINT user_to_answer FOREIGN KEY (user_id) REFERENCES user (user_id),
CONSTRAINT question_to_answer FOREIGN KEY (question_id) REFERENCES question (question_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
In this scheme I do not show the restriction that the user cannot answer his own question. I consider such a restriction to be meaningless. But if you need in it nevertheless then you may add it by creating 2 triggers (BEFORE INSERT and BEFORE UPDATE) on answer table.
The error you are getting is exactly as it says, you are trying to add another constraint with the symbol userid but you already have one with that name on the users_ques table.
As per 13.1.20.5 FOREIGN KEY Constraints
The CONSTRAINT symbol value, if defined, must be unique in the
database. A duplicate symbol results in an error similar to: ERROR
1005 (HY000): Can't create table 'test.fk1' (errno: 121).
So, you either need to assign a database unique name to your constraint or allow the server to assign one for you. If you want to explicitly name them use expressive names that are unlikely to collide. Something like FK_<table_name>_<column_name>.
Also, probably a copy and paste error, but your users_ans looks completely wrong. ansid appears to be typical surrogate key but is then used as the foreign key to users_ques.quesid in your constraint. It looks like you are missing userid and quesid. There's a similar issue with your constraint and columns on users_ques
/* Allowing the server to create the indices and auto-name the constraints */
CREATE TABLE `users_ans` (
`ansid` int UNSIGNED NOT NULL AUTO_INCREMENT,
`quesid` int UNSIGNED NOT NULL,
`userid` int UNSIGNED NOT NULL,
`ans` varchar(200) NOT NULL,
PRIMARY KEY (`ansid`),
FOREIGN KEY (`quesid`)
REFERENCES `users_ques` (`quesid`),
FOREIGN KEY (`userid`)
REFERENCES `users` (`userid`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/* Explicitly naming indices and constraints */
CREATE TABLE `users_ans` (
`ansid` int UNSIGNED NOT NULL AUTO_INCREMENT,
`quesid` int UNSIGNED NOT NULL,
`userid` int UNSIGNED NOT NULL,
`ans` varchar(200) NOT NULL,
PRIMARY KEY (`ansid`),
INDEX `idx_users_ans_quesid` (quesid),
INDEX `idx_users_ans_userid` (userid),
CONSTRAINT `FK_users_ans_quesid`
FOREIGN KEY `idx_users_ans_quesid` (`quesid`)
REFERENCES `users_ques` (`quesid`),
CONSTRAINT `FK_users_ans_userid`
FOREIGN KEY `idx_users_ans_userid` (`userid`)
REFERENCES `users` (`userid`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
If users can only have one answer per question then you can drop the current surrogate key in favour of the natural key on (quesid, userid) -
/* This option only applies if a user can only answer a question once */
CREATE TABLE `users_ans` (
`quesid` int UNSIGNED NOT NULL,
`userid` int UNSIGNED NOT NULL,
`ans` varchar(200) NOT NULL,
PRIMARY KEY (`quesid`, `userid`),
INDEX `idx_inv_primary` (`userid`, `quesid`), -- probably needed for joins in both directions and will be used by `FK_users_ans_userid`
CONSTRAINT `FK_users_ans_quesid`
FOREIGN KEY (`quesid`)
REFERENCES `users_ques` (`quesid`)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT `FK_users_ans_userid`
FOREIGN KEY (`userid`)
REFERENCES `users` (`userid`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
As show in this last example, I prefer to include the referential actions, even when using the default, as it makes the intent clear.
Here's a little db<>fiddle
Your QUESTION table seems to be inappropriately named. As per your title above the create table statement, questions would appear to be the obvious name for the table.
I do not understand your second question, nor why you would want to add the userid to the "QUESTION TABLE". If you would like more help please add more detail to your question to clarify the issues.

Creating composite primarykey using a foreignkey and a non key attribute

This is my auto generated code after creating the batch table. while inserting data to this table
BatchID=1,Course_CourseID=1
BatchID=1,Course_CourseID=2
it is creating an error saying "Duplicate entry '1' for key 'BatchID_UNIQUE'".
I'm using C# 2010 express windows application as well as MySQl 5.1
My table schema is here
CREATE TABLE `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`),
KEY `fk_Batch_Course1` (`Course_CourseID`),
CONSTRAINT `fk_Batch_Course1` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Well, the error message quite clearly refers to this string:
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`)
So what you have to do is either drop this index (with...
ALTER TABLE `batch` DROP INDEX `BatchID_UNIQUE`
... command, or just exclude this line from the table's definition (in CREATE TABLE).
All that said assuming that you really don't need your batch ids to be unique (in other words, there's no logical error in your INSERT statement. That seems to be the case, though: pair BatchID-Course_CourseID is already defined as unique (via PRIMARY KEY).
Try it this way. Drop your batch table and then run this sql. Rightly answered that you can not have two same vaues for a unique key. So I removed the unique key line as well.
CREATE TABLE IF NOT EXISTS `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
KEY `Course_CourseID` (`Course_CourseID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `batch` ADD CONSTRAINT `batch_ibfk_2` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseId`) ON DELETE NO ACTION ON UPDATE NO ACTION;

mysql - foreign key cascade update

I have a question about how to update a field on cascade with a second field as constraint.
The structure is this (I removed the unnecessary columns):
Table nodes with columns idNode and idDimension (together they form the primary key).
Table forces with columns idForce (PK), idNode (foreign key to nodes.idNode) and idDimension.
Cascade update and delete on everything.
The problem in this structure that it seems to appear is this:
If in nodes I have an entry like (1, 1) and one like (1, 2) and in forces (1, 1, 1) and (1, 1, 2) and I update or delete first entry from nodes both entries in forces will be affected.
I need to affect only the one that also has the corresponding idDimension. How can I modify current structure to do that?
Edit: Tables - Nodes:
CREATE TABLE IF NOT EXISTS `nodes` (
`idNode` varchar(11) NOT NULL,
`idDimension` int(10) unsigned NOT NULL,
`idNetwork` int(10) unsigned NOT NULL DEFAULT '0',
`level` int(11) unsigned NOT NULL DEFAULT '0',
`energy` bigint(20) DEFAULT NULL,
`resources` bigint(20) unsigned NOT NULL DEFAULT '0',
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`order` tinyint(3) DEFAULT '0' COMMENT 'energy 0\nassemble 1\nupgrade 2',
`core` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`idNode`,`idDimension`),
KEY `network_dimension` (`idDimension`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Node table';
Forces:
CREATE TABLE IF NOT EXISTS `forces` (
`idForce` bigint(10) unsigned NOT NULL AUTO_INCREMENT,
`idNode` varchar(11) NOT NULL,
`idDimension` int(10) unsigned NOT NULL,
`drones` bigint(20) DEFAULT NULL,
`stance` tinyint(3) DEFAULT NULL COMMENT '0 - defense\n1 - neutral\n2 - attack \n\nIf planet is parano and you are not allied to owner you can only be in attack.\n\nIf owner is allied you can only be in defense or neutral.\n\nIf you are owner you can only be in defense.',
`order` tinyint(3) DEFAULT '0' COMMENT 'extract energy 1\nbuild node 2\nreplicate 3\nmove 4',
`value` text,
PRIMARY KEY (`idForce`),
KEY `idNode` (`idNode`,`idDimension`),
KEY `idDimension` (`idDimension`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Constraints for table forces
ALTER TABLE `forces`
ADD CONSTRAINT `forces_ibfk_2` FOREIGN KEY (`idDimension`) REFERENCES `nodes` (`idDimension`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_forces_nodes1` FOREIGN KEY (`idNode`, `idDimension`) REFERENCES `nodes` (`idNode`, `idDimension`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `forces_ibfk_1` FOREIGN KEY (`idNode`) REFERENCES `nodes` (`idNode`) ON DELETE CASCADE ON UPDATE CASCADE;
My constraints are not working as I would like so feel free to ignore them :).
There are two strange foreign key (forces_ibfk_1 and forces_ibfk_2) which refers to non unique fields. Remove them -
ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_1;
ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_2;
Then recreate fk_forces_nodes1 that refers to unique pair of fields with CASCADE action option -
ALTER TABLE forces
DROP FOREIGN KEY fk_forces_nodes1;
ALTER TABLE orces
ADD CONSTRAINT fk_forces_nodes1 FOREIGN KEY (idNode, idDimension)
REFERENCES nodes(idNode, idDimension) ON DELETE CASCADE ON UPDATE CASCADE;

mysql won't allow foreign key

Many people had this problem already, but there was no fitting solution in other posts.
I have two tables, one named "sales", the other named "host_flags". I would like to have a foreign key for host_flags.sales_id to sales.id, but mysql won't let me! I have primary indexes defined in each table, so I wonder why...
The host_flags table already has a foreign key on the column host_id, but even when I tried and created the foreign key for the sales id first, it wouldn't let me.
The tables look like:
CREATE TABLE `sales` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`creation` datetime DEFAULT NULL,
`lastupdate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
CREATE TABLE `host_flags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`host_id` int(11) DEFAULT NULL,
`sales_id` int(11) DEFAULT NULL,
`creation` datetime DEFAULT NULL,
`lastupdate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `host_id6` (`host_id`),
CONSTRAINT `host_id6` FOREIGN KEY (`host_id`) REFERENCES `hosts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `hosts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`creation` datetime NOT NULL,
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32225 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
I get this error message:
MySQL said: Can't create table 'primarydata.#sql-191_1' (errno: 150)
Thanks!
Charles
SOLUTION FOUND
All ints of the primary indexes have to be either signed or unsigned - not mixed.
Typically:
I like to declare the FK constraints outside of the table definition after all tables have been constructed.
ALTER TABLE `tbl`
ADD CONSTRAINT `constr`
FOREIGN KEY `fk_id` REFERENCES `ftbl`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE;
This way I can make sure the problem isn't something like the datatype of tbl.fk_id not being the same as the one of ftbl.id (including UNSIGNED as #Devart said). Or not having declared ftbl.id as unique. Regardless of the order of declaration of the tables.
After i do this i can integrate the constraint back into the table definition and take into account the order in which the tables need to be created to allow the constraint to be added.
You problem:
-- creating the sales table
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-- creating the host_flags table
`sales_id` int(11) DEFAULT NULL,
-- the sales.id is declared as unsigned
-- the host_flags.sales_id is declared signed
Additonally to Recursed's answer:
There is a requirement that foreign keys contstraints' names must be unique in database scope. Maybe changing the name will work?
There is also a huge thread on MySQL community forums about the problem containing several solutions for some specific situations.
Possible two errors:
Reference and referenced columns must have the same type - int(11) unsigned
Unknown referenced table hosts.

Foreign Key not working: Error code 1005, SQL state HY000: Can't create table

I have two tables I have created and I'm adding the foreign key constraint after the fact.
The two tables are defined as such:
CREATE TABLE `user` (
`user_id` int(11) NOT NULL auto_increment,
`user_ad_id` varchar(500) default NULL,
`user_name` varchar(100) NOT NULL,
`login_id` varchar(100) default NULL,
`email` varchar(256) NOT NULL,
`personal_config` int(10) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE personal_config ADD CONSTRAINT personal_config_fk_user FOREIGN KEY
(config_id) REFERENCES user(personal_config);
And I keep getting the same error but can't figure it out. I've searched all the related threads to this.
Your FK config_id can't be an autoincrement field, that doesn't make much sense right? That field reflects a value in the foreign table, it cannot be set arbitrarily in the local table.
I think this is what you want:
ALTER TABLE user ADD CONSTRAINT personal_config_fk_user FOREIGN KEY (personal_config) REFERENCES personal_config(config_id);
Your ALTER TABLE statement is backward. Since personal_config.config_id is an auto_increment primary key, the foreign key should be defined in the users table against personal_config, not in personal_config against the users table.
ALTER TABLE users ADD CONSTRAINT user_fk_personal_config
FOREIGN KEY (personal_config)
REFERENCES personal_config(config_id);
if you set your user table field personal_config is primary key then it is possible to execute
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id), FOREIGN KEY
(config_id) REFERENCES user(personal_config)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;