How can I add a "ON DELETE CASCADE" - mysql

I already have my forein keys and so on. I only need to add the ON DELETE CASCADE Option. How can I do that? Something with Alter Table?
I'm using mysql with phpmyadmin

I don't know which version of phpMyAdmin you're using, but on the 4.5.2 version, here's how it works if you want to do it without manually writing the SQL query :
Select your table
Go to Structure tab
Go to Relation view "sub-tab"
Define your constraints
Save your changes
Note that this is not possible with the MyISAM storage engine (seems to be the default one on my installation) and you have to select the InnoDB one :
Select your table
Go to Operations tab
Change Storage Engine to InnoDB
Save
For the older phpMyAdmin versions, I know that it was slightly different, as the Relation view was accessible by a link below the table structure.

The simplest way would be to delete the current constraint and add new one with ON DELETE
To delete: ALTER TABLE mytable DROP FOREIGN KEY 'fk_anothertable'
Then create it again:
ALTER TABLE mytable
ADD CONSTRAINT 'fk_anothertable'
FOREIGN KEY ('aColumn' )
REFERENCES 'anotherTable' ('aColumn' )
ON DELETE CASCADE

Unfortunately, you can only create and drop constraints using alter table, you cannot change an existing one. There is no separate alter constraint command either. Therefore all you can do is drop the foreign key and recreate it adding the on delete cascade clause.

Related

Automatic connection of a new table in a existing Mysql database

I have a schema on my db where there are some tables. I have to create a table into this schema and i have to connect it with the others already present on the schema.I make an example:
Tables already present:
SCHOOL(IdSchool,NumStud,IdCountry);
SHOP(IdShop,IdCountry);
New table:
Country(IdCountry,....);
I want to know if there is an automatic mode to connect them (it means not to set the foreign key manually).
I want to know if there is an automatic mode to connect them (it means not to set the foreign key manually).
No.
How is the DBMS to know that Country.IdCountry and SCHOOL.IdCountry are given the same name with the intention to be connected, instead of just accidentally?
You'll have to use ALTER TABLE ... ADD FOREIGN KEY (...) REFERENCES ...1 to explicitly create the foreign key in the existing table.
1 Or ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY (...) REFERENCES ....

On delete restrict mysql is not working

I want to prevent deleting from parent table when he has children in other tables that.
I make like this
ALTER TABLE constant_det_tb
ADD CONSTRAINT fk_idparent
FOREIGN KEY (idparent)
REFERENCES constant_tb(id) ON DELETE RESTRICT
When I delete from parent constant_tb table, it delete the rows even the table has reference to another tables and it has records reference to it.
Make sure you have InnoDB as storage engine for all affected tables.
Check this (if not already) : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
ON DELETE RESTRICT
reference option is all you need to achieve this.
Checking of foreign keys could be disabled for current session.
It can be enabled with
SET FOREIGN_KEY_CHECKS = 1;

Adding constraints in phpMyAdmin

I feel like I'm being stupid, but I can't find anywhere on the phpMyAdmin interface to add constraints to foreign keys e.g. CASCADE ON DELETE
I've looked for similar questions on here and on the phpMyAdmin wiki but I can't find anything about it.
I realise I could do this via the query interface, but I'd like to know how to do it through the graphical interface.
First, you should have your storage engine as InnoDB. Then select a table and go to 'Structure' tab.
Under the table you will see 'Relation view', click it. From there you could add constraints.
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
RESTRICT
A value cannot be updated or deleted when a row exists in a foreign key table that references the value in the referenced table. Similarly, a row cannot be deleted as long as there is a reference to it from a foreign key table.
NO ACTION
NO ACTION and RESTRICT are very much alike. The main difference between NO ACTION and RESTRICT is that with NO ACTION the referential integrity check is done after trying to alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE statement. Both referential actions act the same if the referential integrity check fails: the UPDATE or DELETE statement will result in an error.
SET NULL
The foreign key values in the referencing row are set to NULL when the referenced row is updated or deleted. This is only possible if the respective columns in the referencing table are nullable. Due to the semantics of NULL, a referencing row with NULLs in the foreign key columns does not require a referenced row.
Firstly, you should choose storage engine as InnoDB.
Follow this way: click database_name -> More -> Designer

mysql drop foreign key without table copy

I have an InnoDB table claims which has about 240 million rows. The table has a foreign key constraint: CONSTRAINT FK78744BD7307102A9 FOREIGN KEY (ID) REFERENCES claim_details (ID). I want to delete the table claim_details as quickly as possible.
Based on some experimentation it seems that if I use SET foreign_key_checks = 0; drop claim_details and then re-enable foreign keys, mysql will continue to enforce the constraint even though the table no longer exists. So, I believe I must drop the constraint from the table.
I have tried to use ALTER TABLE claims DROP FOREIGN KEY FK78744BD7307102A9 to drop the constraint and the query has been in a state of "copy to tmp table" for over 24 hours (on a machine with no other load). I don't understand why dropping a constraint requires making a copy of the table. Is there any way to prevent this?
mysql version 5.1.48.
Starting with MySQL 5.6, MySQL supports dropping of foreign keys in-place/without copying. Oracle calls this Online DDL.
This table lists all Online DDL operations and their runtime behavior.
From my experience, dropping foreign keys and the corresponding constraints on a 600GB table is almost instantaneous. With 5.5 it would probably have taken days.
The only disadvantage that I am aware of is, that 5.6 does not allow you to reclaim table space. I.e. if you are using innodb_file_per_table, that file will not shrink when you drop indices. Only the unused data in the file will grow. You can easily check using SHOW TABLE STATUS, and the Data_free column.
I think there is no a good way to drop that foreign key
http://dev.mysql.com/doc/refman/5.5/en/innodb-create-index-limitations.html
"MySQL 5.5 does not support efficient creation or dropping of FOREIGN KEY constraints. Therefore, if you use ALTER TABLE to add or remove a REFERENCES constraint, the child table is copied, rather than using Fast Index Creation." This probably refers also to older versions of mysql.
I think the best method will be to dump data from claims with mysqldump, recreate table without foreign key referencing to claim_details, disable key check with SET foreign_key_checks = 0; in case you have other foreign keys and import back data for claims. Just remember to make separate dumps for data and structure so you don't need to edit this huge file to remove foreign key from table creation syntax.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I tried this in mysql:
mysql> alter table region drop column country_id;
And got this:
ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to
'./product/region' (errno: 150)
Any ideas? Foreign key stuff?
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN
KEY (country_id) REFERENCES
country (id) ON DELETE NO
ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1;
And finally an:
alter table region drop column
country_id;
And you are good to go!
It is indeed a foreign key error, you can find out using perror:
shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.
In your case, it is most likely cause something is referencing the country_id column.
You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.
If the foreign key does exist, and you are still getting this error try the following:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
// Drop the foreign key here!
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
This always does the trick for me :)
Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
here in DROP KEY instead of DROP FOREIGN KEY,
hope it will help.
Thanks
I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.
However, there is an easy "hack" for fixing this issue:
Before you execute your command(s) you first have to disable the foreign key constraints check using this command:
SET FOREIGN_KEY_CHECKS = 0;
Then you are able to execute your command(s).
After you are done, don't forget to enable the foreign key constraints check again, using this command:
SET FOREIGN_KEY_CHECKS = 1;
Good luck with your endeavor.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.
The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.
In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.
My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.
I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?
I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.
I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.
In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:
Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.
Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.
Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;
Now you can execute the drop statement which shall execute successfully.
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
averageRatings= FOREACH groupedRatings GENERATE group AS movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;
If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.