Adding a foreign key to a table - mysql

I haven't practised SQL in a while and I forgot how to add a foreign key to my table
mysql> alter table students
add foreign key fk_unit(unitid)
references unit(unitid)
on delete no action
on update cascade;
ERROR 1072 (42000): Key column 'unitid' doesn't exist in table
I'm wondering why this is the case? My unit table has a primary key called unitid, why does this keep happening?

Try this one it should work....
ALTER TABLE students
ADD CONSTRAINT FK_UnitId FOREIGN KEY (unitid)
REFERENCES unit(unitid);

Try this
ALTER TABLE Students
ADD FOREIGN KEY (unitid)
REFERENCES unit(unitid)

Your query is correct. Looks like field 'unitid' is missing from 'students' table or it has a different name.

Related

How to fix error in MySQL : 1452 - Cannot add or update a child row: a foreign key constraint fails

I run sql query in Navicat, so got error;
Query:
ALTER TABLE `customer_eav_attribute`
ADD CONSTRAINT `CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID`
FOREIGN KEY (`attribute_id`)
REFERENCES `eav_attribute` (`attribute_id`)
ON DELETE CASCADE;
Error:
1452 - Cannot add or update a child row: a foreign key constraint
fails (`caterin1_test`.`#sql-dd4_13`, CONSTRAINT
`CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID`
FOREIGN KEY (`attribute_id`)
REFERENCES `eav_attribute` (`attribute_id`)
ON DELETE CA)
How can I fix it?
I think there is no linked id in eav_attribute table and customer_eav_attribute table.
You must check eav_attribute table and customer_eav_attribute table (best way: plz delete eav_attribute and customer_eav_attribute and then insert data again).
You can find solution.
This is usually happening when you try to source file into existing database. Drop two tables(customer_eav_attribute, eav_attribute). Please create table again.
CREATE TABLE t1
(id INTEGER);
CREATE TABLE t2
(t1_id INTEGER,
CONSTRAINT FOREIGN KEY (t1_id) REFERENCES t1 (id));
And then set like this.
ALTER TABLE `customer_eav_attribute`
ADD CONSTRAINT `CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID`
FOREIGN KEY (`attribute_id`)
REFERENCES `eav_attribute` (`attribute_id`)
ON DELETE CASCADE;
The parent table must exist before you define a foreign key to reference it. you must define the tables in the right order: Parent table first, then the child table. If both tables references each other, you must create one table without FK constraints, then create the second table, then add the FK constraint to the first table with ALTER TABLE.

Cannot alter a column and make it a foreign key

I have two tables, employee and tbl_feedback. What I wanted to do is to add id as a foreign key in tbl_feedback. I already have an id column on my tbl_feedback so I tried altering it using this:
ALTER TABLE tbl_feedback
ADD FOREIGN KEY (id) REFERENCES employee(id);
When I hit go, I only get "Cannot add foreign key constraint". Am I doing it wrong?
tbl_feedback
employee
Reference table must have a PK and that PK fields should not be NULL
So, first modify referenced table if required
For example,
ALTER TABLE TblReference
Alter column refid int NOT NULL
ALTER TABLE TblReference
ADD constraint PK_TblReference_RefId primary key (refid)
Then simply add the Foreign Key constraint
ALTER TABLE TblSource
ADD CONSTRAINT FK_TblSource_Id FOREIGN KEY (id)
REFERENCES TblReference (refid)

adding 2nd foreign keys in one table - MySql

I want to add 2nd foreign key on my existing table 'tbl_subcaste', its already having one 'fk caste caste_id' ass shown below:
now i want to add another 'fk religion religion_id' on this table as shown below :
but MySql giving me this error after doing this:
ALTER TABLE `tbl_subcaste`
ADD CONSTRAINT `fk religion religion_id`
FOREIGN KEY (`religion_id`) REFERE `sanskrut`.`tbl_religion`(`religion_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Error: #1022 - Can't write; duplicate key in table '#sql-534_f7'
I can't understand, why this is not alloeing me to add another kf ?
It seems foreign key name already exist, so just change it and try as per below-
ALTER TABLE `tbl_subcaste`
ADD CONSTRAINT `fk religion religion_id100`
FOREIGN KEY (`religion_id`) REFERE `sanskrut`.`tbl_religion`(`religion_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Even you should follow a standard to avoid this issue as you can keep name as "fk_tablename_columnname".
Further you can use below query to get all key names and other useful information.
SELECT constraint_Schema AS mydb, table_name AS child_table,constraint_name AS foreign_key_name, referenced_table_name AS master_table
FROM information_Schema.REFERENTIAL_CONSTRAINTS
WHERE constraint_Schema='mydb' AND table_name='mytable';
I think you have missed the syntax "REFERENCES". Try the below query
ALTER TABLE tbl_subcaste
ADD CONSTRAINT `f.k` FOREIGN KEY (`religion_id`) REFERENCES sanskrut.tbl_religion(`religion_id`) ON UPDATE CASCADE ON DELETE NO ACTION;

SQL Add foreign key to existing column

If I am using the following SQL command in SQL Server 2008 to update a table with a foreign key constraint:
ALTER TABLE Employees
ADD FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id)
UserID being my FK column in the Employees table. I'm trying to reference the UserID in my ActiveDirectories table. I receive this error:
Foreign key 'UserID' references invalid column 'UserID' in referencing
table 'Employees'.
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
Maybe you got your columns backwards??
ALTER TABLE Employees
ADD FOREIGN KEY (UserID) <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id) <-- this needs to be a column of the ActiveDirectories table
Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?
Then your command should be:
ALTER TABLE Employees
ADD FOREIGN KEY (ID) <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID) <-- column in table "ActiveDirectories"
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
In the future.
ALTER TABLE Employees
ADD UserID int;
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
ALTER TABLE Faculty
WITH CHECK ADD CONSTRAINT FKFacultyBook
FOREIGN KEY FacId
REFERENCES Book Book_Id
ALTER TABLE Faculty
WITH CHECK ADD CONSTRAINT FKFacultyStudent
FOREIGN KEY FacId
REFERENCES Student StuId
way of foreign key creation correct for ActiveDirectories(id), i think the main mistake is you didn't mentioned primary key for id in ActiveDirectories table
If the table has already been created:
First do:
ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);
Then:
ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

how can i modify foreign key?

I'm wondering if it's possible to modify a Foreign Key?
FOREIGN KEY (member) REFERENCES scores (level) ON DELETE CASCADE,
And I would like to change it to:
FOREIGN KEY (member, subject) REFERENCES scores (level, subject) ON DELETE set null,
Is it possible?
You cannot modify the key in a single statement, see the ALTER TABLE syntax, in which there is no ALTER CONSTRAINT available.
You must use 2 ALTER TABLE statements to accomplish what you want.
Delete the key in the first one using an ALTER TABLE DROP FOREIGN KEY.
Re-create it with the new columns in the second, using an ALTER TABLE ADD CONSTRAINT FOREIGN KEY.
You can encapsulate both within a single transaction to make an atomic modification.
In MySql, you can accomplish that by following Tom Tresansky response, which will give us this syntax:
ALTER TABLE `table_name` DROP FOREIGN KEY `key_name`;
ALTER TABLE `table_name` ADD CONSTRAINT `constraint_name` FOREIGN KEY (`new_key_name`)
REFERENCES `other_table_name` ('other_table_id') ON UPDATE CASCADE ON DELETE CASCADE;
have you tried the alter table command?
http://www.w3schools.com/sql/sql_foreignkey.asp