use of foreign key in MySQL - mysql

, If I have (A,B,C) as PK in parent table and (B,C)[unique] are foreign keys and Primary Key in child table with delete cascade enabled, If I delete a record containing (B,C) from parent table will that delete all the records from child table?

By Definition a Forign Key has to be the same as the PK that it refers to. Your columns in the child table (B,C) do not match the PK of the parent table (A,B,C) and therefore cannot be considered an FK back to that parent.
Cascading deletes will have no impact where a FK-->>PK relationship does not exist, which is the case here, so the answer is no.

Related

PhpMyAdmin error #1452 - Cannot add or update a child row: a foreign key constraint fails

What I want to do is put a Foreign Key from users_table column id into users_order table in the column user_id but when I try to do it says this. what did I do wrong or is there any other way to add foreign key to table in PhpMyAdmin ?
#1452 - Cannot add or update a child row: a foreign key constraint fails (`users`.`#sql-4830_792`, CONSTRAINT `#sql-4830_792_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user_order` (`user_id`))
Users
According to the docs,
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.
The error you see indicates that you are trying to add a new row to a child table, for which mo matching row is present in your parent table. To fix it, you can either add the row in your parent table before inserting a row in your child table, or remove NOT NULL constraints (if any) and insert a NULL value in the corresponding column. Once you do it, you will be able to add the foreign key constraint.
Your error said that
the value that you are inserting into the foreign key does not exists in the parent table.
so before insertion foreign value into child table make sure your value is in parent table
The value should be the same in the primary and index key columns.

update 1to many many child record when parent is updated

I have a parent table "DROP" with a compound key that is unique
the child table "DROP_MATERIAL" can have 0-many records with the same compound key as a foreign
key with a primary key that is generated and never used
If a DROP column is updated I want to update each of the related child records
Any one have any ideas on how to do this?

MySQL set ID of primary child with constraint

I have two MySQL tables where the primary relationship between the two is one-to-many. I also need a one-to-one relationship in the parent_table with the ID for the primary record from the child_table. You can kind of think of it as like a dad having lots of kids but having one kid that's his favorite ;P. Is it possible to setup a DB constraint such that a parent can have the ID of a child only if that child is a child of the parent?
parent_table (One)
id: Primary Key
primary_child_id: {ID from child table}
child_table (Many)
id: Primary Key
parent_table: {ID from parent table}
EDIT: The primary child is optional and child records will only be created for an already existing parent. The child_table can certainly be created after the parent_table.
Yes, it's possible, but it's tricky.
CREATE TABLE parent_table (
id INT PRIMARY KEY,
primary_child_id INT,
FOREIGN KEY (primary_child_id) REFERENCES child_table(id)
);
CREATE TABLE child_table (
id INT PRIMARY KEY,
parent_id INT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES parent_table(id)
);
This is a circular reference, so you end up having a chicken-and-egg problem.
I resolve this by making the parent_table.primary_child_id a NULLABLE column, so you can create a parent row even before there are any child rows to reference. If you use NULL in the foreign key column on a given row, it's not a violation of the constraint.
The other tricky part is defining the tables in a circular reference relationship, when creating them as new tables. So you have to leave out one or the other constraint definition until both tables are defined, and then ALTER TABLE to add the missing constraint.
CREATE TABLE parent_table (
id INT PRIMARY KEY,
primary_child_id INT
);
CREATE TABLE child_table (
id INT PRIMARY KEY,
parent_id INT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES parent_table(id)
);
ALTER TABLE parent_TABLE
ADD FOREIGN KEY (primary_child_id) REFERENCES child_table(id);
the parent [shouldn't be allowed to] have a favorite child that isn't his.
Okay, if you need the parent to reference only child records that reference itself:
ALTER TABLE child_table
ADD UNIQUE KEY (parent_id, id);
ALTER TABLE parent_TABLE
ADD FOREIGN KEY (id, primary_child_id) REFERENCES child_table(parent_id, id);
If you create the index in the child table before creating the foreign key, then the foreign key can use that index instead of creating a redundant index.
If I'm understanding correctly, a trigger which raises a SIGNAL should work:
DELIMITER $$
CREATE TRIGGER parent_child BEFORE INSERT ON parent_table
FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT 1 FROM child_table WHERE id = new.id)
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Constraint failed';
ENF IF;
END;
$$
I'm not sure how you're choosing which table should get a record first when each depends on the other. So instead of this trigger you might prefer to write a stored procedure to create the "primary" relationship and validate it also with a SIGNAL.
Yes. You want the child's ID changes/deletions to cascade up to the parent's "favorite child" field, and the parent's ID changes/deletions to cascade down to all its children.
Your parent table should have id and favchild, where id is its primary key index. You would then make a foreign key for favchild that references the child table's primary key.
On the child table, you would make a parent field with a foreign key that references the parent table's id. Then you can have many children with one parent, and one child is the parent's favorite.
However, in order to do this, you need to disable foreign key constraints when you create the parent, because you will need to create at least one child at the same time.
Edit
If the parent must make sure favchild is actually a child: Since the parent row is added first, it would only be updated with favchild by some application logic. In which case you can do the check during that update. The only constraint from that point on would be if favchild were to change parents. So for that your parent table could have two extra columns instead of one: favchild_id and favchild_parent_id. Make those a combined index, with a combined foreign key that references the two columns of the child. ON UPDATE SET NULL. The only drawback here is if the child's ID were to change, it would also be nulled instead of cascaded to the parent.

Getting complicated about foreign key

I am a beginner in innoDB and not very good in database. I m getting confused about foreign keys. I just want to know is:
If I delete a PK( fk on another table)
is the FK on child table also deleted?
So how about if I delete FK on child table?
Record in parent table also deleted?
Also, if I ADD a new record to parent table
child table also added?
How about i add to child table?
How about if i update data?
Please help me, I am very confused about foreign key reference in innoDB database . Guide me to the easiest way. Thanks.
Assuming that the foreign key constraints are defined, supported by the storage engine and are enabled, (i.e. MySQL variable foreign_key_checks = 1, Oracle foreign key constraints enabled and not deferred, etc.)
Q: If I delete a PK( fk on another table) , is the FK on child table also deleted ?
A: If the DELETE rule is specified as CASCADE, then a delete on the parent table will also perform delete operation on the child table. If the DELETE rule is specified as RESTRICT, and there's rows in the child table that reference the parent key, then the DELETE operation will raise an error.
(EDIT: For the sake of completeness, we note that "SET NULL" is another option for an UPDATE or DELETE rule.)
Q: If I delete a row from the child table with a reference to a row in the parent table, is the row in the parent table also deleted ?
A: No. Deleting rows in the child table will have no affect on row in the parent table.
Q: If I INSERT a new row to parent table, will a row also be added to the child table>
A: No. Rows are not automatically inserted to child tables. It's valid (relational database-wise) to have a parent row that does not have any child rows referencing it.
Q: If I INSERT a row to the child table ?
A: No. An insert to the child table does not automatically insert a row to the parent table. (Any non-null value of the foreign key column being inserted to the child table will be validated; the database will verify that there already exists a row in the parent table with a matching value. If there's not, then the INSERT will fail with an error.)
Q: What if I UPDATE values of the foreign key column in the child table.
A: Same as with an insert, the new value will be validated before the update operation proceeds.
Q: What if I UPDATE the value of the primary key in the parent table?
A: If the UPDATE rule on the foreign key is specified as CASCADE, then the related rows in the child table will also be updated, to preserve the relationship between the rows. If the UPDATE rule is RESTRICT, and there are related rows in the child table, the update operation will raise an error.
Foreign keys are designed for enforcing referential integrity. They basically disallow inserts/updates in the child table when the new non-null values of the foreign key column doesn't reference a row in the parent.
The UPDATE and CASCADE rules defined on the foreign key constraint determine the behavior of UPDATE and DELETE operations on the parent table.
What your'e asking about is cascading the update/deletion to the child element.
The docs : http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Example :
CONSTRAINT FOREIGN KEY (jobAbbr) REFERENCESffxi_jobType(jobAbbr) ON DELETE CASCADE ON UPDATE CASCADE
the "ON DELETE CASCADE" means that when the key is deleted, all the FK's are deleted aswell, this is very useful for data integrity. It's however not automatic.
Deleting a foreign key will not delete the key it's based upon either way.

DELETE CASCADE on a child row delete parent?

I have 3 tables.
The last two tables have a foreign key to the first on the same field.
Both foreign keys are set to UPDATE CASCADE, DELETE CASCADE.
When I delete a child-row in the second table, the parent row in the first table remains unchanged.
But when I delete a child-row in the third table, the first row in the table is deleted!
Foreign keys should not behave in the same way as both daughters?
My guess is that table 2 uses MyISAM tables (which do not support foreign keys) while the other two tables are using the InnoDB engine (which do support foreign keys).
From the documentation:
Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. The parent and child tables must both be InnoDB tables. They must not be TEMPORARY tables.