遇到MySQL主键问题并添加索引(错误#1064)

时间:2015-04-15 05:16:52

标签: mysql indexing key

CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL INDEX,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL)

我收到此错误:

#1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'INDEX附近使用正确的语法,     成功TINYINT UNSIGNED NOT NULL,     Time_Created DATETIME NOT NULL)'在第3行

3 个答案:

答案 0 :(得分:1)

要在CREATE TABLE语句中定义内联索引,您需要将其放在单独的'create definition'行中:

CREATE TABLE registers(
  User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
  IP INT UNSIGNED NOT NULL,
  INDEX(IP),
  Success TINYINT UNSIGNED NOT NULL,
  Time_Created DATETIME NOT NULL
);

SqlFiddle

您还可以将索引定义放在表定义like so

之外
CREATE INDEX IX_registers_ip ON registers(IP);

将索引命名为良好做法,以便可以准确引用。

答案 1 :(得分:0)

尝试这一点 - 在MySQL语法中,INDEX定义不能包含在字段定义中:

CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL,
INDEX `ip_1` (`ip`)
)

或者 - 有时为了可读性而首选,您可以在创建表后在单独的语句中创建索引:

CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL
);

CREATE INDEX ip_1 ON registers (ip);

答案 2 :(得分:0)

您的语法必须是:

CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL ,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL,
INDEX (IP )
)

有关create table语句的更多信息,请参阅官方mysql documentation