I had already created the database and all tables with foreign key constraints, but I had a column in parent table which was unique and was part of composite key, so I had to drop all foreign key constraints from all child tables and then dropped the unique constraint on parent table.
Now when I am adding foreign key constraint back to all child tables, it gives error: foreign key constraint is incorrectly formed, although I have checked both my parent and child table columns and they are of same type using same engine, unicode and all. But still this is thrown.
When I checked the table structure of child table, it has an index defined for the foreign key and the column is child column foreign key, so I tried after removing it but still error.
Query
ALTER TABLE `child_table` ADD CONSTRAINT FOREIGN KEY `fk_parent_table_child_table_column_name` (child_table_column_name)
REFERENCES `parent_table`(parent_table_column_name) ON DELETE RESTRICT ON UPDATE NO ACTION;
both columns are VARCHAR PRIMARY KEY and NOT NULL
If more information is required please ask.
EDIT
So far I have tried to dropped the index, dropped the PRIMARY KEY CONSTRAINT from child table and dropping the column then adding it back with VARCHAR(14), NOT NULL, still no success.
EDIT 2
Also tried to add the child column in primary key and then tried to apply foreign key constraint, no success so far.
Since no one answered and I couldn't find a solution to my problem I had to drop the child foreign keys and then remove the parent composite key so as to remove the parent column which was VARCHAR(14) and then again create foreign keys with new primary key.
Related
I have this MySql database table:
tbl_project
id
project_name
parent_id
If a project is a 'parent', parent_id is 0.
Now I'm trying to add a self referencing foreign key
CONSTRAINT `FK_tbl_project_tbl_project` FOREIGN KEY (`parent_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE
When I try to insert a new record,
SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (mydbname.#sql-3539_d7d, CONSTRAINT FK_tbl_project_tbl_project FOREIGN KEY (parent_id) REFERENCES tbl_project (id) ON DELETE CASCADE)
Basically I just want all the children to be deleted when I delete the parent. What am I missing here?
When you enter any value into the parent_id column of a new row, the foreign key requires that there is a row where id has that value, because that's how foreign keys work.
If you want to use a foreign key with your self-referencing relationship, you should use NULL instead of 0 for the parent_id of a row that has no parent to reference. Foreign keys ignore NULL.
I have foreign key, but I don't set it as a foreign key in phpmyadmin. it just a INTEGER type column.
Question : What is the difference result between setting or not setting it as foreign key in phpmyadmin?
The FOREIGN KEY constraint enables some automatic checks by the database engine.
If you don't specify it as a foreign key, you won't get an error if you try to insert a value that doesn't exist in the other table. And you can't make use of options like ON DELETE CASCADE, which automatically deletes the row in the child table if the parent row is deleted.
I'm designing a website of book library for my project in php.
Anyways I have three tables named books,users and savebook.
Table book has following columns: "bookid", "title","author" "genre" and "summary".
And table users has following columns userid, username, password, and name.
Users can save books as favorites and those saved books are saved in the table named savebook with columns bookid and userid which are foreign key to table book and users
I used following query for that:
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid);
and
ALTER TABLE savebook
ADD CONSTRAINT usid_bkid
FOREIGN KEY (userid)
REFERENCES users(userid);
Now the problem is whenever i try to delete a book from table book using query
DELETE FROM books
WHERE bookid=1;
I get this message:
1451 - Cannot delete or update a parent row: a foreign key constraint fails (booklibrary.savebook, CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid))
How do i delete a book from table book which also deletes the related row in table savebook?
To get the behavior you describe, you can specify
ON DELETE CASCADE
as part of the foreign key definition.
Reference: http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
If you were to modify your foreign key constraint bkid_usid (on the booksave table), then the delete statement that you show
DELETE FROM books WHERE ...
Would cause MySQL to delete the rows in booksave that have a foreign key values that reference rows being removed from books.
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid)
ON DELETE CASCADE
;
Make note of that last line I added to the ALTER from the original question, it is an optional part of the foreign key definition (there is also ON UPDATE ...). By default, when not specified, I believe MySQL treats it as NO ACTION or RESTRICT (those two are effectively the same as far as I know) instead of CASCADE. Full documentation found at http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
An interesting question :)
I think the problem is caused by the so called "referential integrity".
That means, that you are not able to delete a dataset, which primary key is used in another tables dataset as foreign key. If you could do this, some foreign keys of the table savebook would refer to a dataset in table books, that doesn't exist anymore.
So first you have to delete all datasets in savebook, where the bookid is the same one as of the book you want to delete and after that, you can delete this dataset from books. ;)
You have applied constraints to the tables. You need to tell MySQL to delete referenced entries from "savebook" table if any entry is deleted from "book" table.
ALTER TABLE savebook ADD CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid) ON DELETE CASCADE
i've tried to set the primary and foreign key using the method that i learn at http://fellowtuts.com/php/setting-up-foreign-key-in-phpmyadmin/ but an error came up stating that
#1025 - Error on rename of '.\sistem_akaun\#sql-1b70_7d' to '.\sistem_akaun\detail_akaun' (errno: 150 - Foreign key constraint is incorrectly formed)
can i know what's the problem here?sorry if this question sounds stupid,just a newbie
Check to make sure that the Primary Key you are referencing exists. If, in your main table, you have id_main = 0 on your main table, where id_main is a foreign key referencing id_ref (which is the primary key of the other table) but you have reference ref_id = 1 and no 0 value, you will get an error.
Check to make sure your foreign key is the primary key of the other table.
Check to make sure they are the same data type, length, unsigned status. Sometimes these matter sometimes not.
Sometimes I've had trouble where both Foreign Key and Primary Key are both named "id". This can be a problem depending on what software/methods you are using.
You may find it easier to specify a foreign key manually, in SQL.
ALTER TABLE Table
ADD FOREIGN KEY (Column)
REFERENCES TableToReference (ColumnToReference)
(Where Table is the table you wish to add a foreign key to)
#itsfawwaz, You can also do this by below way. Check below example.
Example : (Table Orders)
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Above is sample example, you can use your own table fields !
Let me know if still you have any issues.
Can anyone help me with this database error, I'm inserting data on a table named
subjectdetails(
subjectid int primarykey,
subject varchar(50),
semid int //foreign key from the table semester
departmentid int(11) // foreign key from the table department
)
Now, when i insert a subject it only shows the error on SEMID like the below error
Cannot add or update a child row: a foreign key constraint fails
(`studentcorner/subjectdetails`, CONSTRAINT `subjectdetails_ibfk_1` FOREIGN KEY
(`SEMID`) REFERENCES `semester` (`SEMID`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Please help me with this..
The error is indicating that you have a foreign key constraint which cannot be satisfied. Specifically, you're trying to insert a subjectdetails entry with an invalid semid column. The value you're using for semid is invalid because that value cannot be found inside the semester table. I know this because your error message states as much.
To fix this error, ensure that the value you're trying to insert for the semid column actually exists in the semesters table first.
I would suggest going to the documentation and re-read the section on Using Foreign Key Constraints. The relevant quote from that page regarding your issue is this (emphasis mine):
For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.