Damian
Damian

Reputation: 3050

Right syntax for creating a foreign key

I use MySql 5.5.8 and I can't find out how should I write which field need to be a foreign key refererece. For example:

CREATE TABLE IF NOT EXISTS `answers` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`answer` text COLLATE utf8_polish_ci NOT NULL ,
`user` tinyint( 4 ) DEFAULT NULL ,
`created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ,
`html_template_id` int( 11 ) NOT NULL ,
PRIMARY KEY ( `id` ) ,
CONSTRAINT html_template_id FOREIGN KEY `html_template_id` REFERENCES `html_templates` ( `id` )
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_polish_ci AUTO_INCREMENT =1;

And I get an error message:

 #1064 - 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 'REFERENCES `html_templates`(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=' at line 10

Upvotes: 1

Views: 2910

Answers (1)

Jan S
Jan S

Reputation: 1837

use

CONSTRAINT html_template_id FOREIGN KEY (`html_template_id`) REFERENCES `html_templates` ( `id` )

i.e. the foreign key field should be in brackets

Upvotes: 3

Related Questions