I'm creating new database and I want to create a table Supplier_StockOut:

CREATE TABLE StockOut_Supplier (
  idStockOut_Supplier INT NOT NULL,
  idStockOut INT NOT NULL,
  idSupplier INT NOT NULL,
  idTransactionType INT NOT NULL,
    FOREIGN KEY (idSupplier) REFERENCES Suppliers(idSupplier)
    ON DELETE SET NULL
    ON UPDATE CASCADE,
  FOREIGN KEY (idStockOut) REFERENCES StockOuts (idStockOut)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  FOREIGN KEY (idTransactionType) REFERENCES TransactionTypes(idTransactionType)
    ON DELETE SET NULL
    ON UPDATE CASCADE
) ENGINE=innodb DEFAULT CHARACTER SET=utf8 COLLATE=utf8_polish_ci;

Result:

ERROR 1005 (HY000): Can't create table 'stocktest.stockout_supplier' (errno: 150)

All tables that those key references are defined properly. For example:

CREATE TABLE Suppliers (
  idSupplier INT NOT NULL auto_increment PRIMARY KEY,
  name VARCHAR(64) NOT NULL
) ENGINE=innodb DEFAULT CHARACTER SET=utf8 COLLATE=utf8_polish_ci;

Even if I leave only the one Foreign Key (for instance to the Suppliers) - result will remain the same.

Same thing happens when I'm trying to create table without foreign keys and do ALTER TABLE later to add them. I noticed I can add them without ON DELETE ON UPDATE clauses but not with them.

EDIT: There are many InnoDB databases using a lot of foreign keys on this server so I guess it's not server-configuration related problem.

Any ideas?

有帮助吗?

解决方案

In your StockOut_Supplier table, columns idSupplier and idTransactionType are set not to accept NULLs but by foreign key declarations you're telling it to set their values to NULL on deletion of the primary key.

You might want to set those to RESTRICT or CASCADE instead.

其他提示

ON DELETE SET NULL is the problem because you set NOT NULL on idSupplier But try running script like this:

CREATE TABLE StockOut_Supplier (
  idSupplier INT NOT NULL,
  CONSTRAINT FOREIGN KEY (idSupplier) REFERENCES Suppliers(idSupplier)
    ON UPDATE CASCADE
);

ALTER TABLE StockOut_Supplier
  ADD FOREIGN KEY (idSupplier) REFERENCES Suppliers(idSupplier)
    ON DELETE SET NULL;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top