How to avoid adding duplicate foreign key constraints - mysql

I would to know if it is possible to avoid adding several times the same foreign key constraint?
Example: if I execute 3 times the query below, the constraint will exist with 3 times in phpmyadmin... It would be great that it would be rejected the second and third time I apply that query.
ALTER TABLE `my_items_details`
ADD FOREIGN KEY (`items_id`) REFERENCES `my_items`(`item_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;

You can give a explicit name to the foreign key, instead of letting MySQL assigning a default name for you.
ALTER TABLE `my_items_details`
ADD FOREIGN KEY `my_foreign_key` (`item_id`) REFERENCES `my_items`(`item_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;
Since two objects of the same type cannot have the same name, this query will generate an error the second time you run it:
Error: ER_FK_DUP_NAME: Duplicate foreign key constraint name 'my_foreign_key'
Demo on DB Fiddle

To prevent duplicate foreign key values in a table in a database, you can define a unique index or unique constraint on the foreign key field in the table.
In PHPMyAdmin, you can create a unique index or constraint on a foreign key field by following these steps:
Select the table from the list of tables in the left-hand panel.
Click on the "Structure" tab.
Scroll down to the field that you want to define the unique index or constraint on.
Click on the "Index" drop-down menu for the field, and select "Unique".
Alternatively, you can use the following SQL query to create a unique index on a foreign key field called item_id in a table called items:
ALTER TABLE items ADD UNIQUE (item_id);

Related

How to delete a foreign key thats references multiple columns in mySQL

I have a foreign key that references two columns in a child table. Id like to delete the foreign key but mySQL just hangs and nothing happens:
Here is the output from SHOW CREATE TABLE table_name:
KEY FK_animal_index (animal_type,food_index),
CONSTRAINT FK_animal_index FOREIGN KEY (animal_type, food_index)
REFERENCES animal_schedules (animal_type, food_index)
ENGINE=InnoDB
I have tried deleting this foreign key using:
`ALTER TABLE table_name DROP FOREIGN KEY FK_animal_index;`
`ALTER TABLE table_name DROP FOREIGN KEY animal_type;`
ALTER TABLE section_configuration DROP FOREIGN KEY FK_animal_index,
DROP KEY (animal_type, food_index);
AND
ALTER TABLE section_configuration DROP FOREIGN KEYFK_animal_index, ADD CONSTRAINT FK_animal_type FOREIGN KEY (animal_type) REFERENCESanimal_schedules(animal_type) ON DELETE SET NULL;
Others have mentioned that ON DELETE not being set can prevent you changing key values (mySQL will reject the change if ON DELETE is not set to anything)
But to no avail, mySQL just hangs and 30 minutes later still nothing. The database is very small at the moment so removing the FK should be fast.
The answer to this question was not about primary keys at all.
I had to stop my program from accessing the table in order to make modifications to it.
In mySQL db, you can add tables and add columns at any time, but if you want to change a column or remove a column, it must not be in use by any program or it will hang indefinitely.

Mysql showing error while creating primary key and foreign key relation between two tables despite of using index

I have two tables in Mysql named customer_details and transaction table.
I have one column named account_no( primary key in customer_details) and want to relate with account_no field(foreign key in transaction table).
But it is showing error saying Foreign key relation could not be added.
I tried creating index in both columns but still its not working.
ALTER TABLE transaction
ADD INDEX FK_Transaction_AccountNo_idx (AccountNo ASC);
ALTER TABLE transaction
ADD CONSTRAINT FK_Transaction_AccountNo
FOREIGN KEY (AccountNo)
REFERENCES customer_details (AccountNo)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
collation of both table and column should be equal

foriegn key constrant fails

what does the below error mean
{"info":{"error":{"errorInfo":["23000",1452,"Cannot add or update a child row: a foreign key constraint fails (`cs_test_db`.`accountinfo`, CONSTRAINT `fk_accinfo_accttypeid` FOREIGN KEY (`account_type_id`) REFERENCES `accounttype` (`accounttype_id`) ON DELETE NO ACTION ON UPDATE NO)"]},"unique_code":""}}
The error means that you are trying to update data in a table that have a constraint of foreign key. Actually, your current table is linked to another table that have a column with data that is the only ones to be present in it.
In order to see the link, please run this command: SHOW ENGINE IMMODB STATUS; and search for "Latest foreign key error". It will show you the parent table. Or run this other command: SHOW CREATE TABLE Accountinfo; to see the foreign key constraint with parent table.
Then, do a select on the parent table and check the data on the column you are using as a constraint... data values present are different from what you are trying to update.

Foreign Key Tables Updates

I just started learning SQL so I am a bit confused.
If I have Table A that has a primary key : CustomerID & Table B with foreign key CustomerID
I added the foreign key constraint by using CASCADE so that the foreign key should update or delete automatically when primary key is deleted or updated.
However, it only works for delete. When I add a new record in the primary field table, that record is not shown in the foreign key table, why is that ?
Corresponding rows are updated or deleted in the referencing table
when that row is updated or deleted in the parent table. CASCADE
cannot be specified if a timestamp column is part of either the
foreign key or the referenced key. ON DELETE CASCADE cannot be
specified for a table that has an INSTEAD OF DELETE trigger. ON UPDATE
CASCADE cannot be specified for tables that have INSTEAD OF UPDATE
triggers.
As mention in MSDN. They have mentioned the only update and delete operation of primary key table will affect the Foreign key table's column. If any insert made to primary key, it will not affected the foreign key. Since the Main objective in primary key and foreign key relationship
"An each every record is available in the foreign key table, it should contain corresponding record should be present in the primay key table and vice versa is not applicable".
If you insert any record to foreign key table that it will throws foreign referential integrity error. It will not allows you to insert a record in the foreign table unless and until you will corresponding record in the primary key table.
for information take look in following in MSDN links
http://msdn.microsoft.com/en-us/library/ms179610.aspx
Note:
if you want to achieve this functionality then you have write a logic in Stored procedure or trigger.
No,is not automatic add in your foreign key table , it's not make sense , for example if you have two table ,"City" and "People" , People in the City , so there must be a FK refer for People , if you add record in City e.g. New York , How is database know who's need to insert to People table?How many people? , and what this people properties? e.g. People Name?
So database can't do that automatic , you have to do it manually!

How to add a foreign key in MySQL on WAMPserver?

I can't figure how to indicate that a column is a foreign key in WAMPserver. I suppose I could write the MySQL query for that, but I would think that there is also a way to do that using the user interface (PHPMyAdmin)...?
Creating a foreign key constraint relies on your storage engine being set to something that can support it (such as InnoDB). In PHPMyAdmin, you can set this in "Operations" for the table with the "Storage Engine" option. Once that's complete:
Make sure you've assigned an index to the column you'll be assigning a foreign key to.
Click on "Relation view" under the table details on the "Structure" tab.
Assign your foreign key constraint and decide on the actions for DELETE and UPDATE.
you can add a foreign key for the existing table by the following query
ALTER TABLE sample.employee
ADD FOREIGN KEY (dno)
REFERENCES sample.department(dnumber)
here sample. employee is your current table and sample .department is existing table which has the value for your foreign key dno is current table forign key and dnumber is existing table primary key.