Reputation: 13
CREATE TABLE hoofdtoonder
(
id INT NOT NULL,
idondersoorten INT FOREIGN KEY REFERENCES `ondersoort`(`id`) NOT NULL,
)
//making table but the error is with the references its on a mysql database someone please help
It says error at FOREIGN KEY REFERENCES ondersoort(id) NOT NULL
. But I don't know what's wrong with the syntax.
Upvotes: 0
Views: 59
Reputation: 562310
MySQL does not support inline foreign key references.
It's true that the SQL language allows for syntax like @Mureinik suggested:
idondersoorten INT NOT NULL REFERENCES `ondersoort`(`id`)
But you will find that MySQL parses this and ignores it. InnoDB does not support inline foreign key syntax. If you now run SHOW CREATE TABLE hoofdtoonder
, it'll show this:
CREATE TABLE `hoofdtoonder` (
`id` int(11) NOT NULL,
`idondersoorten` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Where did the REFERENCES go? It was silently discarded. This is actually a beef I have with MySQL, that it recognizes some valid constraint syntax, but ignores it. It doesn't even show you a warning. It just defines the table without the constraint.
In MySQL, you must declare a foreign key as a table-level constraint, like this:
CREATE TABLE hoofdtoonder (
id INT NOT NULL,
idondersoorten INT NOT NULL,
FOREIGN KEY (idondersoorten) REFERENCES `ondersoort`(`id`)
);
Upvotes: 0
Reputation: 311228
There are several things wrong here:
foreign key
, just references
.not null
clause should come before the references
clause.To put it all together:
CREATE TABLE hoofdtoonder (
id INT NOT NULL,
idondersoorten INT NOT NULL REFERENCES `ondersoort`(`id`)
);
Upvotes: 2