I'm doing a tutorial to learn perl/catalyst and it seems to be a little out of date. I'm trying to alter an already existing column, which was previously a primary key (Already dropped the primary key), into a foreign key. I've tried a bunch of different configurations of the syntax and can't seem to pin it down. This is my most recent attempt:
ALTER TABLE book_author (
MODIFY book_id INTEGER
ADD CONSTRAINT FOREIGN KEY book_id
REFERENCES book(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Any advice is appreciated.
You use parentheses like you are doing in a CREATE TABLE statement, but not in an ALTER TABLE statement.
You are also missing a comma between the MODIFY and the ADD CONSTRAINT lines.
And you are missing parentheses around the column book_id which is the subject of the constraint.
The following works:
ALTER TABLE book_author
MODIFY book_id INTEGER,
ADD CONSTRAINT FOREIGN KEY (book_id)
REFERENCES book(id)
ON DELETE CASCADE
ON UPDATE CASCADE;
This syntax is documented on the official MySQL site: http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
Related
here is my table structure
I would like that parent_forum would save an id of parent forum, which is the ID of the same table id column value. As you can see both columns have the same type. My table engine is InnoDB, I try the following query to add a constraint.
ALTER TABLE `forums` ADD CONSTRAINT `parent_forum constraint` FOREIGN KEY (`id`) REFERENCES `codeigniter`.`forums`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
and I get an error that is written on the title.
What is actually wrong here? Category_id successfully works with other table ID value.
I think this is the syntax you are looking for:
ALTER TABLE forums ADD CONSTRAINT parent_forum_constraint
FOREIGN KEY (parent_forum) REFERENCES codeigniter.forums(id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
The column in parentheses is the one that refers to the column after the references. Also, don't put spaces in names, unless you have a really good reason. Code is much more readable without all the backticks.
I use MySQL with InnoDB engine. I double-checked type of columns. But always have:
Error Code: 1215. Cannot add foreign key constraint
I tried:
ALTER TABLE `mail`.`boxes`
ADD CONSTRAINT FK_id
FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
ON UPDATE NO ACTION
ON DELETE NO ACTION;
and
ALTER TABLE `mail`.`boxes`
ADD FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
Nothing works(((
Please, help, what I am doing wrong (except choosing MySQL :-) )?
If table contains data then you are not able to add foreign key you drop table object and recreate
use below reference for the same
Basics of Foreign Keys in MySQL?
To check what exactly the problem is, use:
SHOW ENGINE INNODB STATUS\G
There is section "last foreign key error". Look at: http://dev.mysql.com/doc/refman/5.0/en/innodb-monitors.html
My guess is that data type od mail.boxes (id) and mail.users (id) is not the same. (E.g. smallint in one table and integer in second one).
Data in table on which you're trying to create FK could possibly also be problem (are your mailbox ids the same as id of existing users?)
I keep getting an error "Incorrect index name 'f7'" using MySQL and I've narrowed it down to the following:
First I create the table,
CREATE TABLE testTable (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
f7 INTEGER NOT NULL,
FOREIGN KEY (f7) REFERENCES testTable2 (id) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB;
And then elsewhere,
ALTER TABLE testTable ADD UNIQUE f7;
This has led me to believe that this has to do with a duplicate index (?) I just can't figure out how to fix it. Many thanks.
Give it a name, so it doesn't conflict with the foreign Key index
ALTER TABLE `testtable` ADD UNIQUE INDEX `foo` (`f7`);
An incorrect index name error is given when you're attempting to create a new index with the same name as an existing index.
In MySQL, when you create a foreign key, as you're doing with FOREIGN KEY (f7) REFERENCES testTable2 (id) ON DELETE CASCADE ON UPDATE CASCADE, an index is auto-created as well. In this case, the name is defaulted to f7.
The foreign key is created as a non-unique index; your second command: ALTER TABLE testTable ADD UNIQUE (f7); will make this index unique - not add a second one.
To verify what indexes already exist on the table, you can use the following:
SHOW INDEXES FROM testTable;
If you're receiving this error, there is likely additional code elsewhere that is attempting to create an index named f7. You can attempt to find it, or change your CREATE TABLE syntax to name the key something different so that it doesn't cause conflicts:
FOREIGN KEY fk_testTable_f7 (f7) REFERENCES testTable2 (id) ON DELETE CASCADE ON UPDATE CASCADE
In this example, I used fk_testTable_f7 and you should now have a non-unique index on the table named fk_testTable_f7. To make it unique, you can use your existing ALTER command as you want the column to be unique - not the foreign key itself.
In phpMyAdmin when i try to add foreign key some error occurs and does not tell what is wrong. Just says "FK fails".
Can any one tell what is the problem?
Error
SQL query:
ALTER TABLE `hotel` ADD FOREIGN KEY ( `type_id` ) REFERENCES `hotel`.`hotel_type` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`hotel`.`#sql-cfc_e`, CONSTRAINT `#sql-cfc_e_ibfk_2` FOREIGN KEY (`type_id`) REFERENCES `hotel_type` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Be sure the columns of both tables are of the same data-type:
hotel.hotel type_id int(11) unsigned # type_id column of hotel table
hotel.hotel_type id int(11) unsigned # id column of hotel_type table
If they are not of the same type then you won't be able to add your FK constraint.
-- Edit --
Based on your response, the columns are the same data-types, so that means you have an invalid value in the hotels.type_id column (value doesn't exist in the hotel_types table). Check the values in your hotels.type_id column and make sure they exist in your hotel_types.id column.
Well there can be a lot of reasons for which you can't create a foreign key. I have found a very interesting article, which I suggest you to read it closely. Maybe something will help you. You can also find very important infos in the MySQL manual, regarding the "FOREIGN KEY Constraints".
Hope this helped.
There are some data in your table that no longer exist in other table, and actually this is against foreign key rules.
If you don't need their data, truncate both tables, and add the foreign key otherwise you should add all the foreign keys one by one.
Here is a query that will find those rows:
select sourcecode_id from
sourcecodes_tags tags left join sourcecodes sc on tags.sourcecode_id=sc.id
where sc.id is null;
Remove the ON DELETE CASCADE ON UPDATE CASCADE
Although this is old, I thought I would share that the way I resolved this was by checking that the encoding and the collation were the same on both sides which for some reason were different.
This fixed the issue.
I'm wondering if it's possible to modify a Foreign Key?
FOREIGN KEY (member) REFERENCES scores (level) ON DELETE CASCADE,
And I would like to change it to:
FOREIGN KEY (member, subject) REFERENCES scores (level, subject) ON DELETE set null,
Is it possible?
You cannot modify the key in a single statement, see the ALTER TABLE syntax, in which there is no ALTER CONSTRAINT available.
You must use 2 ALTER TABLE statements to accomplish what you want.
Delete the key in the first one using an ALTER TABLE DROP FOREIGN KEY.
Re-create it with the new columns in the second, using an ALTER TABLE ADD CONSTRAINT FOREIGN KEY.
You can encapsulate both within a single transaction to make an atomic modification.
In MySql, you can accomplish that by following Tom Tresansky response, which will give us this syntax:
ALTER TABLE `table_name` DROP FOREIGN KEY `key_name`;
ALTER TABLE `table_name` ADD CONSTRAINT `constraint_name` FOREIGN KEY (`new_key_name`)
REFERENCES `other_table_name` ('other_table_id') ON UPDATE CASCADE ON DELETE CASCADE;
have you tried the alter table command?
http://www.w3schools.com/sql/sql_foreignkey.asp