CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
I dont understand the meaning of putting ENGINE = INNODB here, and why do we use ON DELETE CASCADE?
engine=innodb will ensure you get foreign key support. The default MyISAM engine doesn't support foreign keys. On delete cascade will remove the child row if the referenced row in the parent table is removed.
MySQL is the DB engine. It can use multiple storage engines. MyISAM is the default storage engine for MySQL and it does not support foreign keys. InnoDB is another storage engine that does support foreign keys. You must specify ENGINE=InnoDB because MySQL will use MyISAM by default.
ON DELETE CASCADE will delete all rows in a table that have a foreign key that references a key that is deleted. I think it is dangerous and defeats a lot of the purpose of foreign key restriction, so I would avoid using it, but this is just my personal opinion.
Say you have:
+-------+-------+
| ordID | proID |
+-------+-------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
+-------+-------+
And on OrdersItems it has FOREIGN KEY (proID) REFERENCES Products (proID) ON DELETE CASCADE.
Then if someone runs
DELETE FROM Products WHERE proID = 2
Then rows with ordID 4 and 5 will also be deleted (it cascades).
Related
I have three tables in MySQL v5.6 created by:
CREATE TABLE tm (
id INT AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE th (
id INT AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE tr (
id INT AUTO_INCREMENT,
tm_id INT,
th_id INT,
PRIMARY KEY (id),
CONSTRAINT fk_1 FOREIGN KEY (tm_id) REFERENCES tm (id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_2 FOREIGN KEY (th_id) REFERENCES th (id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO tm (id) VALUES (101);
INSERT INTO tm (id) VALUES (102);
INSERT INTO th (id) VALUES (1);
INSERT INTO tr (tm_id, th_id) VALUES (101,1), (102,1);
So in the end I have three tables with following data:
th
| id |
|----|
| 1 |
tr
| id | tm_id | th_id |
|-----|---------|-------|
| 11 | 101 | 1 |
| 12 | 102 | 1 |
tm
| id |
|------|
| 101 |
| 102 |
And what I am trying to do is to delete all of them with one SQL query:
DELETE th, tr, tm
FROM th
LEFT JOIN tr ON tr.th_id = th.id
LEFT JOIN tm ON tr.tm_id = tm.id
WHERE th.id = 1;
As a result th and tr tables will be blank but tm will be left with id=102
+------+
| id |
+------+
| 102 |
+------+
And I am not searching for better query but trying to understand why tm.id=101 was deleted but tm.id=102 was left in the table?
This is the result of the InnoDB storage engine which is used (as default) to create the tables and the foreign key constraints.
Check the demo without foreign keys and the result is that all rows of all tables are deleted.
You would get the same result, even with the foreign key constraints if you created the tables with the MyISAM storage engine.
Check the demo.
But for the InnoDB storage engine and the foreign key constraints, as it is mentioned in 13.2.2 DELETE Statement:
If you use a multiple-table DELETE statement involving InnoDB tables
for which there are foreign key constraints, the MySQL optimizer might
process tables in an order that differs from that of their
parent/child relationship. In this case, the statement fails and rolls
back. Instead, you should delete from a single table and rely on the
ON DELETE capabilities that InnoDB provides to cause the other tables
to be modified accordingly.
so what you get may be the result of a rollback for the deletion of id = 102 of tm, because the order of the tables processed is such that it would violate a foreign key constraint.
Check the demo.
I have two tables (A, B) with a foreign key from B to A.
So A is my parent table and B my child.
I now insert a row in B before the parent row exists in A. So I set the foreign key to an id I know parent A will have, but which is not existing right know. To achieve that I use the option 'SET foreign_key_checks = 0', which allows to set a foreign key in the child B without the existens of the key in the parent A.
My question is, what will happen, if I add the row in A with the missing primary key. Will the foreign key <-> primary key connection work and will it be as fast as normal? Or do I have to drop the fk key and rebuild it?
I use InnoDB and MySQL 5.5.
... and I know that is probably very bad practice...
Or short:
I have a parent and a child table, linked by a foreign key. I add the child first, what happens if I add the parent later?
My question is, what will happen, if I add the row in A with the
missing primary key. Will the foreign key <-> primary key connection
work and will it be as fast as normal? Or do I have to drop the fk key
and rebuild it?
If you will add missing record into parent table, the FK constraint will work as it should be. You will actually solve the data inconsistency.
There is no need to recreate FK.
I tried it myself by creating an example.
CREATE TABLE `parent` (
`idparent` int(11) NOT NULL,
PRIMARY KEY (`idparent`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `parent` (
`idparent` int(11) NOT NULL,
PRIMARY KEY (`idparent`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET foreign_key_checks = 0;
INSERT INTO child (idchild, parentid) VALUES (1,1),(2,2),(3,3),(4,4),(5,5);
SET foreign_key_checks = 1;
INSERT INTO parent (idparent) VALUES (1),(2),(3),(4),(5);
Next, I used explain to get an idea, if the index is used:
EXPLAIN SELECT * from parent p
join child c on c.parentid = p.idparent;
+----+-------------+-------+-------+-----------------+-----------------+---------+----------------------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+-----------------+-----------------+---------+----------------------+------+--------------------------+
| 1 | SIMPLE | p | index | PRIMARY | PRIMARY | 4 | NULL | 5 | Using index |
| 1 | SIMPLE | c | ref | fk_parentid_idx | fk_parentid_idx | 5 | remove_me.p.idparent | 1 | Using where; Using index |
+----+-------------+-------+-------+-----------------+-----------------+---------+----------------------+------+--------------------------+
So it looks like it uses the index, altough at first the foreign key was not set. Therefore, it should be at least speedwise no problem.
INSERT INTO `area` (
`area_id` PRIMARY KEY,
`area_name`,
`chemist_id`FOREIGN KEY
)
VALUES (
[value-1],
[value-2],
[value-3]
)
I want to create a references to foreign table. but i'm getting the following error:
query:
CREATE TABLE category_ids (id INT, post_id INT,
INDEX par_ind (post_id),
FOREIGN KEY (post_id) REFERENCES post(id)
ON DELETE CASCADE
) ENGINE=INNODB;
SHOW ENGINE INNODB STATUS\G:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-23 00:11:06 7f6f49e7b700 Error in foreign key constraint of table fun/category_ids:
FOREIGN KEY (post_id) REFERENCES post(id)
ON DELETE CASCADE
) ENGINE=INNODB:
Cannot resolve table name close to:
(id)
ON DELETE CASCADE
) ENGINE=INNODB
posts table structure
mysql> describe post;
+-------------+-----------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------------+------+-----+---------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
...
+-------------+-----------------------+------+-----+---------------------+----------------+
22 rows in set (0.00 sec)
Only InnoDB supports Foreign keys, MyISAM doesn't.
Even if it would, you cannot create relations between tables of different type.
Therefore you need to convert the table post into InnoDB. ALTER TABLE post ENGINE = InnoDB;
This error can also come when parent table is partitioned. Removing partitioning from the parent table allows foreign constraint to be created without any problem.
For me works with this.
CREATE TABLE category_ids (id INT, post_id INT references post(id),
INDEX par_ind (post_id)
) ENGINE=INNODB;
I have 1 MySQL Table. It looks like this:
+---------+-------------+--------+
| item_id | parent_id | Name |
+---------+-------------+--------+
| 1 | 0 | Home |
+---------+-------------+--------+
| 2 | 1 | Sub |
+---------+-------------+--------+
| 3 | 2 | SubSub |
+---------+-------------+--------+
If I DELETE item_id 1, I want to delete the rest of the sub also but how can I do it?
I have tried the Foreign Key but it works only if you have 2 tables??
I hope someone can help me in MySQL maybe PHP?
You can, most definitely, use self-referencing foreign keys with MySQL (you don't need multiple tables). However, for any kind of foreign key support, you need to use the InnoDB engine. And my guess is, that you are using the MyISAM engine.
With InnoDB you could create a table, similar to what you have already, including the self-referencing foreign key, like this:
CREATE TABLE `yourTable` (
`item_id` int(10) unsigned NOT NULL auto_increment,
`parent_id` int(10) unsigned default NULL,
`Name` varchar(50) NOT NULL,
PRIMARY KEY (`item_id`),
KEY `FK_parent_id` (`parent_id`),
CONSTRAINT `FK_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `yourTable` (`item_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Then, when you issue a DELETE statement, like:
DELETE FROM `yourTable` WHERE `item_id` = 1;
... it would delete each 'child' row, that has a parent_id of 1 as well. If any of those 'child' rows have children of their own, they'd be deleted too, etc. (that's what the ON DELETE CASCADE means).
Easier actually than thought:
DELETE FROM table WHERE id = # OR parent_id = #; //where # is the same in both places.
Example:
DELETE FROM table WHERE id = 1 OR parent_id = 1;
ALTER TABLE `groups` ADD FOREIGN KEY ( `company_id` ) REFERENCES `summaries`.`companies` (
`id`
) ON DELETE CASCADE ;
MySQL said:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`summaries/#sql-164a_33c`, CONSTRAINT `#sql-164a_33c_ibfk_1` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE)
companies.id is primary auto increment int(11)
company_id is index int(11)
I don't understand the error message. Can anyone shed some light on this?
That means you have at least one row in the child table that references a non-existent row in the parent table.
If you are absolutely sure that you are okay with having a data integrity issue like that, you can add the foreign key by disabling foreign key checks before you run the ALTER TABLE command:
SET FOREIGN_KEY_CHECKS = 0;
I just had this problem, although in a somewhat more specific scenario.
In my case, I had added, to an existing table, a column that I needed to be both nullable and act as a foreign key (i.e., for non-null entries to be bound by a foreign key constraint).
The referenced column looked like this:
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
+-------------+-------------+------+-----+---------+----------------+
and the referencing one like this:
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| bed_id | int(10) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
Turned out that I had forgotten to specify DEFAULT NULL when adding the referencing column to the existing table and so it was automatically filled with zeros, which failed the foreign key constraint.
I changed them to NULL:
update devices set bed_id = NULL where bed_id = 0;
and then successfully added the foreign key constraint. Hope this helps someone
It looks like it tried to copy the groups table to a temp table in the summaries database.
MySQL tried to put the requested constraints on the temp table first. There may possibly be one or more rows in the groups table (hence the temp table also) whose company_id is no longer present in the summaries.companies table.
To verfiy : Try running a LEFT JOIN between groups and summaries.companies WHERE companies.id is NULL. If you get back any rows from that LEFT JOIN, you found the bad rows in the groups table.
Give it a Try !!!
Checks that "companies" table is not empty,if is empty and you have no data at moment.
set SET FOREIGN_KEY_CHECKS = 0;
like Ike said you before.