Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column and make it a foreign key in single MySQL statement?

Tags:

sql

mysql

In mysql, can I add a column and foreign key in the same statement? And what is the proper syntax for adding the fk?

Here is my SQL:

ALTER TABLE database.table  ADD COLUMN columnname INT DEFAULT(1),  FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE; 

...and the accompanying error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE' at line 4

like image 658
VinnieP Avatar asked Oct 09 '09 18:10

VinnieP


People also ask

How do I add a column to a foreign key in a table?

To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.

How do you set a column as foreign key in MySQL workbench?

To add a foreign key, click the last row in the Foreign Key Name list. Enter a name for the foreign key and select the column or columns that you wish to index by checking the column name in the Column list. You can remove a column from the index by removing the check mark from the appropriate column.

Can we add foreign key after table creation?

We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.


2 Answers

Try this:

ALTER TABLE database.table   ADD COLUMN columnname INT DEFAULT(1),   ADD FOREIGN KEY fk_name(fk_column) REFERENCES reftable(refcolumn) ON DELETE CASCADE; 
like image 137
Asaph Avatar answered Sep 29 '22 00:09

Asaph


The following query adds a column by alter query and the constraint query makes it a FK in a single mysql query. You can do it like this,

SYNTAX:

ALTER TABLE `SCHEMANAME`.`TABLE1`  ADD COLUMN `FK_COLUMN` BIGINT(20) NOT NULL,  ADD CONSTRAINT `FK_TABLE2_COLUMN` FOREIGN KEY (`FK_COLUMN`)  REFERENCES `SCHEMANAME`.`TABLE2`(`PK_COLUMN`); 

EXAMPLE:

ALTER TABLE `USERDB`.`ADDRESS_TABLE`  ADD COLUMN `USER_ID` BIGINT(20) NOT NULL AFTER `PHONE_NUMBER`,  ADD CONSTRAINT `FK_CUSTOMER_TABLE_CUSTOMER_ID` FOREIGN KEY (`USER_ID`)  REFERENCES `USERDB`.`CUSTOMER_TABLE`(`CUSTOMER_ID`);  
like image 21
Lucky Avatar answered Sep 29 '22 01:09

Lucky