how can i modify foreign key? - mysql

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

Related

Adding a foreign key to a table

I haven't practised SQL in a while and I forgot how to add a foreign key to my table
mysql> alter table students
add foreign key fk_unit(unitid)
references unit(unitid)
on delete no action
on update cascade;
ERROR 1072 (42000): Key column 'unitid' doesn't exist in table
I'm wondering why this is the case? My unit table has a primary key called unitid, why does this keep happening?
Try this one it should work....
ALTER TABLE students
ADD CONSTRAINT FK_UnitId FOREIGN KEY (unitid)
REFERENCES unit(unitid);
Try this
ALTER TABLE Students
ADD FOREIGN KEY (unitid)
REFERENCES unit(unitid)
Your query is correct. Looks like field 'unitid' is missing from 'students' table or it has a different name.

Alter Table add Foreign Key Reference

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

adding 2nd foreign keys in one table - MySql

I want to add 2nd foreign key on my existing table 'tbl_subcaste', its already having one 'fk caste caste_id' ass shown below:
now i want to add another 'fk religion religion_id' on this table as shown below :
but MySql giving me this error after doing this:
ALTER TABLE `tbl_subcaste`
ADD CONSTRAINT `fk religion religion_id`
FOREIGN KEY (`religion_id`) REFERE `sanskrut`.`tbl_religion`(`religion_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Error: #1022 - Can't write; duplicate key in table '#sql-534_f7'
I can't understand, why this is not alloeing me to add another kf ?
It seems foreign key name already exist, so just change it and try as per below-
ALTER TABLE `tbl_subcaste`
ADD CONSTRAINT `fk religion religion_id100`
FOREIGN KEY (`religion_id`) REFERE `sanskrut`.`tbl_religion`(`religion_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Even you should follow a standard to avoid this issue as you can keep name as "fk_tablename_columnname".
Further you can use below query to get all key names and other useful information.
SELECT constraint_Schema AS mydb, table_name AS child_table,constraint_name AS foreign_key_name, referenced_table_name AS master_table
FROM information_Schema.REFERENTIAL_CONSTRAINTS
WHERE constraint_Schema='mydb' AND table_name='mytable';
I think you have missed the syntax "REFERENCES". Try the below query
ALTER TABLE tbl_subcaste
ADD CONSTRAINT `f.k` FOREIGN KEY (`religion_id`) REFERENCES sanskrut.tbl_religion(`religion_id`) ON UPDATE CASCADE ON DELETE NO ACTION;

MySQL: delete a row ignoring foreign key constraint

so I am working on a few tables and there are some data inconsistency between them... One or two tables have a foreign key constraint on a particular table (call it table X), but that table has multiple rows with the foreign key column.
What I want to do is to remove the duplicated rows in table X, but the foreign key constraint is preventing me from doing this. Is there a way to force delete the rows while ignoring the foreign key constraint since I know what I'm doing?
SET foreign_key_checks = 0;
That will prevent MySQL from checking foreign keys. Make sure to set it back to 1 when you are done though.
Also, you could always drop the foreign key and then add it later if you wanted to only affect a singular key
ALTER TABLE tableName DROP FOREIGN KEY fk;
Simply execute as follows:
Disable foreign key check
SET foreign_key_checks = 0;
Delete your records
DELETE FROM table_name WHERE {conditions};
Enable foreign key check
SET foreign_key_checks = 1;
Credit: https://www.knowledgewalls.com/johnpeter/books/mysql/how-to-ignore-constraints-while-insertupdate-or-delete-records-in-mysql
As some people already pointed out, ignoring a restricting foreign key leaves you with database inconsistencies. Preventing DELETEs is something you want in such cases.
You should better delete depending rows prior to the main query:
DELETE FROM cities WHERE country_id=3;
-- Afterwards you delete rows from the parent table without error:
DELETE FROM countries WHERE country_id=3;
Or, even better, change the foreign key once, so it does the deletion automatically (cascading):
ALTER TABLE cities DROP FOREIGN KEY `fk.cities.country_id`;
ALTER TABLE cities ADD CONSTRAINT `fk.cities.country_id` FOREIGN KEY (country_id)
REFERENCES countries (id) ON UPDATE CASCADE ON DELETE CASCADE;
-- From now on, just delete from the parent table:
DELETE FROM countries WHERE country_id=3;
To expand on the accepted answer, you have to specify the constraint name after DROP FOREIGN KEY
You can check the constraint name by issuing SHOW CREATE TABLE.
> SHOW CREATE TABLE tbl_name
Create Table: CREATE TABLE `tbl_name` (
`id` int(11) DEFAULT NULL,
`foo_id` int(11) DEFAULT NULL,
CONSTRAINT `foo_ibfk_1` FOREIGN KEY (`foo_id`)
)
In this case, "foo_ibfk_1" is the constraint name. So you can write:
ALTER TABLE tableName DROP FOREIGN KEY foo_ibfk_1;

MySQL InnoDB foreign key between different databases

I would like to know if it's possible in InnoDB in MySQL to have a table with foreign key that references another table in a different database ?
And if so, how this can be done ?
I do not see any limitation on https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html.
So just use otherdb.othertable and you will be good.
It's possible : Link to do it
Example (Table1 is in database1 and HelloTable is in database2) :
ALTER TABLE Table1
ADD foreign key FK_table1(ColumnNameFromTable1)
REFERENCES db2.HelloTable(ColumnNameFromHelloTable)
Below is how to add a foreign key on table t2, reference from table db1.historial(codh):
alter table t2
add foreign key FK_t2(micod2)
references db1.historial(codh)
on delete cascade
on update cascade;
ALTER TABLE `tablename1`
ADD CONSTRAINT `tablename1_student_id_foreign`
FOREIGN KEY (`tablename1`.`id`)
REFERENCES `db2`.`tablename2`(`id`)
ON DELETE CASCADE ON UPDATE CASCADE;
if we have table calling answers in db1 and student in db2 calling ramiyusu_offline
we must type as below
ALTER TABLE `answers`
ADD CONSTRAINT `answers_student_id_foreign`
FOREIGN KEY (`id`)
REFERENCES `ramiyusu_offline`.`student`(`id`)
ON DELETE CASCADE ON UPDATE CASCADE;