How to add a foreign key in MySQL on WAMPserver? - mysql

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.

Related

How to avoid adding duplicate foreign key constraints

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);

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 foreign key to MySQL table?

I use MySQL with InnoDB engine. I double-checked type of columns. But always have:
Error Code: 1215. Cannot add foreign key constraint
I tried:
ALTER TABLE `mail`.`boxes`
ADD CONSTRAINT FK_id
FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
ON UPDATE NO ACTION
ON DELETE NO ACTION;
and
ALTER TABLE `mail`.`boxes`
ADD FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
Nothing works(((
Please, help, what I am doing wrong (except choosing MySQL :-) )?
If table contains data then you are not able to add foreign key you drop table object and recreate
use below reference for the same
Basics of Foreign Keys in MySQL?
To check what exactly the problem is, use:
SHOW ENGINE INNODB STATUS\G
There is section "last foreign key error". Look at: http://dev.mysql.com/doc/refman/5.0/en/innodb-monitors.html
My guess is that data type od mail.boxes (id) and mail.users (id) is not the same. (E.g. smallint in one table and integer in second one).
Data in table on which you're trying to create FK could possibly also be problem (are your mailbox ids the same as id of existing users?)

How to alter Foreign Keys in phpMyAdmin

I have set up a Foreign Key in my mysql database with:
ALTER TABLE `gameplayers` ADD CONSTRAINT `FK_GAMENUMBER` FOREIGN KEY (`GameNumber`) REFERENCES `games`(`GameNumber`) ON UPDATE CASCADE ON DELETE CASCADE;
However, I am not sure I want the ON UPDATE and ON DELETE anymore.
So I go into my phpAdmin, click on the edit pencil icon in the Index section of the Structure Tab and I get this:
Warning: ("PRIMARY" must be the name of and only of a primary key!)
Do alterations just have to be done manually? Ie the pencil icon will just not work.
ALSO: Do foreign keys have the same speed bonus effect on mysql searches, similar to Indexes?
Foreign keys require indexes, so effectively, the foreign key constrain creates and index and it can be used to resolve queries just like normal indexes.
I'm not sure which version of phpMyAdmin you are using, I think foreign key constains are supported in newest versions, but it seems your does not list foreign key indexes, and the primary key is not what you are looking for. You can however modify the keys with plain SQL:
ALTER TABLE `gameplayers` DROP FOREIGN KEY FK_GAMENUMBER,
ADD CONSTRAINT `FK_GAMENUMBER` FOREIGN KEY (`GameNumber`) REFERENCES `games`(`GameNumber`) ON UPDATE NO ACTION ON DELETE NO ACTION;

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

So I am trying to add a primary key to one of the tables in my database. Right now it has a primary key like this:
PRIMARY KEY (user_id, round_number)
Where user_id is a foreign key.
I am trying to change it to this:
PRIMARY KEY (user_id, round_number, created_at)
I am doing this in phpmyadmin by clicking on the primary key icon in the table structure view.
This is the error I get:
#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)
It is a MySQL database with InnoDB table engine.
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.
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.
To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.
(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
I had this problem, it is for foreign-key
Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key
Hope that works!
If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.
Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.
You can set some value which is present in the parent table and then adding foreign key worked for me.