创建FOREIGN KEY时出错

时间:2014-03-14 18:04:06

标签: mysql sql reference foreign-keys create-table

CREATE TABLE IF NOT EXISTS `servergraph_server` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    `name` VARCHAR(64) NOT NULL, 
    `ip` VARCHAR(16) NOT NULL, 
    `port` SMALLINT UNSIGNED NOT NULL
)

CREATE TABLE IF NOT EXISTS `servergraph_data` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    `serverid` INT NOT NULL, 
    `time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 
    `fps` SMALLINT UNSIGNED NOT NULL, 
    `replay` TINYINT UNSIGNED NOT NULL, 
    `dropped_packets` INT UNSIGNED NOT NULL, 
    `online` TINYINT UNSIGNED NOT NULL, 
    `clients0` TINYINT UNSIGNED NOT NULL, 
    `clients1` TINYINT UNSIGNED NOT NULL, 
    `clients2` TINYINT UNSIGNED NOT NULL, 
    `clients3` TINYINT UNSIGNED NOT NULL, 
    FOREIGN KEY (`serverid`) REFERENCES `servergraph_server` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)

这是我想要创建的表格。

但我总是在FOREIGN KEY线上收到错误。

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 'FOREIG' at line 1

我正在使用此版本的MySQL:5.5.35-0 + wheezy1

有什么问题?

谢谢,floube

SOLUTION:

ALTER TABLE `servergraph_data` ADD CONSTRAINT `fk_server` FOREIGN KEY (`serverid`) REFERENCES `servergraph_server` (`id`)

而不是CREATE TABLE servergraph_data

中的FOREIGN KEY行

1 个答案:

答案 0 :(得分:0)

在create table语句后放置半冒号:

CREATE TABLE IF NOT EXISTS `servergraph_server` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    `name` VARCHAR(64) NOT NULL, 
    `ip` VARCHAR(16) NOT NULL, 
    `port` SMALLINT UNSIGNED NOT NULL
);

CREATE TABLE IF NOT EXISTS `servergraph_data` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    `serverid` INT NOT NULL, 
    `time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 
    `fps` SMALLINT UNSIGNED NOT NULL, 
    `replay` TINYINT UNSIGNED NOT NULL, 
    `dropped_packets` INT UNSIGNED NOT NULL, 
    `online` TINYINT UNSIGNED NOT NULL, 
    `clients0` TINYINT UNSIGNED NOT NULL, 
    `clients1` TINYINT UNSIGNED NOT NULL, 
    `clients2` TINYINT UNSIGNED NOT NULL, 
    `clients3` TINYINT UNSIGNED NOT NULL, 
    FOREIGN KEY (`serverid`) REFERENCES `servergraph_server` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);