Question

I'm creating a small database so that I can get the hang of MySQL and SQL in general.

I'm not sure what I'm doing wrong but I figured I'd post my code just in case the problem is something syntactical that I'm just not catching.

CREATE TABLE student(
       ID varchar(5) NOT NULL, 
       name varchar(20) NOT NULL, 
       dept_name varchar(20), 
       tot_cred numeric(3,0), 
  PRIMARY KEY(ID), 
  FOREIGN KEY(dept_name) 
    REFERENCES department 
  ON UPDATE CASCADE 
  ON DELETE CASCADE) 
ENGINE = InnoDB;

I have already created the 'department' table that contains the dept_name primary key. I have attempt to continue on without using ENGINE=InnoDB when using foreign key constraints but have--obviously--been unsuccessful.

Could someone please explain to me why MySQL is throwing me an error 1005 errno 150 and how I should fix it using the simplest terms possible?

Was it helpful?

Solution

make sure you adhere to this syntax...

CREATE TABLE parent (
    id INT NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id INT, 
    parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id) 
        REFERENCES parent(id)
        ON DELETE CASCADE
) ENGINE=INNODB;

Make sure your data types are the same on the fk... and you have to say what column in it references in the other table

OTHER TIPS

From mysql docs:

1005 (ER_CANT_CREATE_TABLE)

Cannot create table. If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. If the error message refers to error –1, table creation probably failed because the table includes a column name that matched the name of an internal InnoDB table.

When using REFERENCES you should specify both the refferenced table, and the referrenced row within the table:

example:

REFERENCES departments(id)

Also, for performance causes, it is recommended to use numeric values as foreign keys.

I just had this problem. My solution was to make sure the integer types for the fields I was referencing were both UNSIGNED. If one is SIGNED and the other UNSIGNED you will get this error.

If you want negative numbers then just make sure both are SIGNED, but most likely you will want UNSIGNED. Point is they need to be the same type.

So if you are referencing a primary key in another table, make sure that primary key is an UNSIGNED Integer type.

Then when you create your foreign key make sure the column you are creating it on is of type UNSIGNED Integer as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top