tables related with foreign key are synched with each other - mysql

I am using phpmyadmin for mysql. I have 4 tables project1, project2, project3 and combine table. suppose combine table is connected to all other tables with the foreign keys and we add some data with the help of some background script to project1, prject2, and project3 tables. Is there any way to update the corresponding foreign keys in the combine table automatically ( without manually updating the record). I am using a yii framework for the GUI.
Please suggest some way as I am new to mysql and yii framework.

http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Not fully understanding your question but I think you are referring to ON DELETE and ON UPDATE.
ON DELETE & ON UPDATE options
CASCADE
SET NULL
NO ACTION
RESTRICT
ON DELETE & ON CASCADE are placed as constraints in the FK table and they occur when parent ID is either deleted or updated.
So if you change an id within the projects table and you wish for this change to be reflected in the combine table, you would use ON UPDATE CASCADE.
As a side note, why do you have 4 tables? I can only see the need for 2 tables.
Please note that SQL below may not be syntactically correct.
CREATE TABLE tbl_projects (
id integer NOT NULL PRIMARY KEY AUTO INCREMENT,
name varchar(255),
...
...
);
Method 1 creating a row for each project in the combine table:
CREATE TABLE tbl_combine (
id integer NOT NULL PRIMARY KEY AUTO INCREMENT,
project_id integer,
...
CONSTRAINT `FK_combine_project`
FOREIGN KEY (`project_id`)
REFERENCES `tbl_project` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
);
Method 2:
CREATE TABLE tbl_combine (
id integer NOT NULL PRIMARY KEY AUTO INCREMENT,
project1_id integer,
project2_id integer,
project3_id integer,
...
CONSTRAINT `FK_combine_project1`
FOREIGN KEY (`project1_id`)
REFERENCES `tbl_project` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `FK_combine_project2`
FOREIGN KEY (`project2_id`)
REFERENCES `tbl_project` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `FK_combine_project3`
FOREIGN KEY (`project3_id`)
REFERENCES `tbl_project` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
);
You can also do this via GUI in phpmyadmin by setting the foreign keys as an index by clicking a button, then going to the table relation view and choosing your options.
Hope this helps - I have attached an phpmyadmin image for you to see.

Related

MySql workbench: add Foreign key error

I am trying to add foreign key 'USERNAME' in tutorial table, but there was an error.
Executing:
ALTER TABLE `databse`.`tutorial`
ADD CONSTRAINT `USERNAME`
FOREIGN KEY (`USERNAME`)
REFERENCES `databse`.`register` (`USERNAME`)
ON DELETE CASCADE
ON UPDATE CASCADE;
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1452: Cannot add or update a child row:
a foreign key constraint fails (`databse`.`#sql-e7c_5`, CONSTRAINT `USERNAME` FOREIGN KEY (`USERNAME`)
REFERENCES `register` (`USERNAME`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Statement:
ALTER TABLE `databse`.`tutorial`
ADD CONSTRAINT `USERNAME`
FOREIGN KEY (`USERNAME`)
REFERENCES `databse`.`register` (`USERNAME`)
ON DELETE CASCADE
ON UPDATE CASCADE
Foreign key setting:
Tutorial table setting:
Any ideas ? thank you
I solved it, i created a new 'tutorials' table replace 'tutorial' table, and use same way to add foreign key, it worked! = =
still thank you for your helps !!
as stated here :
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
In the code you show : you try to reference the "USERNAME" column, wich is not a primary key in your last capture
So you can either change your primary key in the register table to USERNAME, or you can change the foreign key to reference TutorialName
You have two table one is child table and second is parent table .So you would need to guarantee that each child column has NULL or has values that present in parent column.
This problem is normally caused by mismatching of values presented in the two columns constrained by the new foreign key.
That is, the value presented in the child table does not have a reference presented in the parent table.
when creating a foreign key, you need to make sure that:
the table type supports foreign key
there is a index on the foreign key column
the types of data of the two columns constrained by a foreign key are similar enough so that they can be converted to each other
the data presented in both columns constrained by a foreign key is consistent.

Issiue with ON DELETE CASCADE?

I have a question about ON DELETE CASCADE, i have made thise tables as an example.
CREATE TABLE shop_articles(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
description TEXT
);
CREATE TABLE shop_articles_images(
id INT AUTO_INCREMENT PRIMARY KEY,
article_id INT,
description VARCHAR(255),
image VARCHAR(255),
FOREIGN KEY (article_id) REFERENCES shop_articles (id)
);
In order to delete all the data affiliated with the main table, i am using this ALTER TABLE command after adding the tables.
ALTER TABLE shop_articles_images
ADD CONSTRAINT shop_articles_images_ibf5
FOREIGN KEY (article_id) REFERENCES shop_articles (id)
ON DELETE CASCADE;
It seams alltough this have been added i cant delete rows from the main table, i dont want to manually delete the other affiliated tables, but delete it when delete from the main table.
Any one have experience with this, or can see what i do wrong here? does this altertable reset when the mysql server is restarted?
I think you have some confusion about how ON DELETE CASCADE works. If your engine is MyISAM, which does not enforce foreign keys, then no cascading deletes will happen. If your engine is InnoDB, then if you delete a record from the main table shop_articles then any records in shop_articles_images which are linked to the main table via a key relationship will also be deleted.

Correct way to remove entry from a SQL table along with the relations

If we have TableA and TableB related by TableAB where TableAB has foreign keys for the first two table, then what's the go-to way of deleting an entry from TableA? Up to now if used a property such as IsActive with a bit to describe if the entry is still valid. However, that makes it a little problematic when there are "ghost entries" in the relation tables, such as TableAB.
How should I proceed?
One chaining table in question.
CREATE TABLE EntradaContadorCliente (
ClaveECC int AUTO_INCREMENT not null,
ClaveCliente int not null,
ClaveContador int not null,
ClaveEntrada int not null,
PRIMARY KEY (ClaveECC),
FOREIGN KEY (ClaveCliente) REFERENCES Cliente(ClaveCliente),
FOREIGN KEY (ClaveContador) REFERENCES Contador(ClaveContador),
FOREIGN KEY (ClaveEntrada) REFERENCES EntradaBitacora(ClaveEntrada)
);
Since TableA and TableB related by TableAB; which means TableAB is a chaining table. One way is to use ON DELETE CASCADE for cascading the delete operation on primary table.
Alternative is to, manually delete the entries from your chaining table once the entry has been deleted from primary table.
You can use a ALTER statement to re-create the FK constraint like
ALTER TABLE `TableAB` DROP FOREIGN KEY FK_KEY_Test;
ALTER TABLE `TableAB` ADD CONSTRAINT FK_KEY_Test FOREIGN KEY ('some_column')
REFERENCES `TableA` ('Test_column1') ON UPDATE CASCADE ON DELETE CASCADE;
From MySQL Documentation:
CASCADE: Delete or update the row from the parent table, and
automatically delete or update the matching rows in the child table.
Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.
first you disable all foreign key with:-
alter table table_name
nocheck constraint fk_constraint
then you delete data in parent table.

Foreign constraint fails for unknown reason

I have a table that has 3 fields that reference the same table for the 3 fields.
CONSTRAINT `fk_form_pago_insc`
FOREIGN KEY (`form_pago_insc` , `form_pago_tit` , `form_pago_col`)
REFERENCES `unisis`.`tbl_forma_de_pago` (`id` , `id` , `id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
This is because one field is the form of payment for the deposit, the second field is the form of payment for the course, and the third field is the form of payment for the certificate.
So all three reference the same table for foreign constraints.
I can't see any issue with this, yet I can't create it. I used MYSQL WORKBENCH to model the entire database. If I try to make a private for each one individually, MYSQL WORKBENCH closes on me. I'm using the most recent version from the website. (6.1.6)
You want three different constraints:
CONSTRAINT `fk_form_pago_insc` FOREIGN KEY (`form_pago_insc`)
REFERENCES `unisis`.`tbl_forma_de_pago` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION;
CONSTRAINT `fk_form_pago_tit` FOREIGN KEY (`form_pago_tit`)
REFERENCES `unisis`.`tbl_forma_de_pago` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION;
CONSTRAINT `fk_form_pago_col` FOREIGN KEY (`form_pago_col`)
REFERENCES `unisis`.`tbl_forma_de_pago` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION;

MySQL and Foreign Keys

I have a question regarding Foreign Keys in an InnoDB Table. I have 4 tables in my database:
Signup:
UID - Primary Key
Afid
Planid
Industryid
Affiliates:
Afid - Primary Key
Plans:
Planid - Primary Key
Industries:
Industryid - Primary Key
SQL I use to add the keys:
CONSTRAINT `FK_signup_industries` FOREIGN KEY (`industryid`) REFERENCES `industries` (`industryid`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_signup_affiliates` FOREIGN KEY (`afid`) REFERENCES `affiliates` (`afid`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_signup_plans` FOREIGN KEY (`planid`) REFERENCES `plans` (`planid`) ON UPDATE CASCADE ON DELETE CASCADE
What my question is:
If I was to delete a plan or an industry on their respective tables would the user in the signup table be deleted? I have tried to find guides on this and they don't explain it very well.
Basically what I need done is that the row in the signup table never to be deleted no matter what. When I use this query:
CONSTRAINT `FK_signup_plans` FOREIGN KEY (`planid`) REFERENCES `plans` (`planid`) ON UPDATE CASCADE ON DELETE NO ACTION
I get this error:
Cannot delete a parent row.
If you need the row in Signup to stay even if you delete the referenced row in Industries, Affiliates, or Plans, then you have two choices:
Do not declare a foreign key constraint. This removes enforcement of referential integrity, but it allows rows to exist in Signup that reference a parent primary key value that no longer exists.
Use ON DELETE SET NULL. This allows the row to stay, but the foreign key value that references the now-deleted parent will be changed.*
For more details see http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
* The standard SQL specification also defines a rule ON DELETE SET DEFAULT, but InnoDB doesn't support this feature.