Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MariaDB: ALTER TABLE syntax to add a FOREIGN KEY?

Tags:

mariadb

what'S wrong with the following statement?

ALTER TABLE submittedForecast
  ADD CONSTRAINT FOREIGN KEY (data) REFERENCES blobs (id);

The error message I am getting is

Can't create table `fcdemo`.`#sql-664_b` (errno: 150 "Foreign key constraint is incorrectly formed")
like image 890
user1774051 Avatar asked Mar 08 '16 10:03

user1774051


People also ask

How do I add a foreign key constraint to an existing table in MariaDB?

In this syntax: First, specify the name of the foreign key constraint after the constraint keyword. MariaDB will implicitly assign a generated name if you skip the constraint clause. Second, specify the name of the foreign key followed by a list of comma-separated column names placed within parentheses.

How do I add a foreign key to the table using alter command?

So if you already created the table student, and now you wish to add Foreign Key you can use the below command to change that: ALTER TABLE dbo. student add constraint Fk_empid foreign key(emp_id) references dbo. emp(id);

How do I manually add a foreign key?

Here's the syntax to create foreign key in MySQL. ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (foreign_key_name,...) REFERENCES parent_table(column_name,...); In the above query, table_name is the the table where you want to add foreign key.

Does MariaDB support foreign key?

Foreign keys have the following limitations in MariaDB: Currently, foreign keys are only supported by InnoDB. Cannot be used with views. The SET DEFAULT action is not supported.


2 Answers

This works for me on MariaDB 10.1.8:

CREATE TABLE `submittedforecast` (
    `id` INT(11) NOT NULL,
    `data` INT(11) NOT NULL,
    PRIMARY KEY (`id`),
    INDEX `data` (`data`)
) ENGINE=InnoDB;    
CREATE TABLE `blobs` (
    `id` INT(11) NOT NULL,
    `content` BLOB NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;
ALTER TABLE submittedForecast
  ADD CONSTRAINT FOREIGN KEY (data) REFERENCES blobs (id);

Can you give your MariaDB version number and a complete example including the CREATE TABLE statements for submittedForecast and blobs?

like image 159
Julian Ladisch Avatar answered Oct 23 '22 21:10

Julian Ladisch


No idea if you already solved this but make sure both engines and collations match between tables (e.g: latin1 to latin1 and InnoDB to InnoDB).

I was having the same issue and by switching these I managed to get it working.

like image 27
David Arguedas Avatar answered Oct 23 '22 22:10

David Arguedas