我有以下查询:
create table bans
(
id int auto_increment primary key ,
reason int not null,
player int not null,
server int not null,
starts timestamp default current_timestamp not null,
ends DATETIME not null,
constraint bans__fk_player
foreign key (player) references players ('id'),
constraint bans__fk_server
foreign key (server) references servers ('id')
);
这将导致:
[2019-01-02 18:35:29] [42000][1064] (conn=75) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''id'),
[2019-01-02 18:35:29] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''id'),
我只想在两者之间建立1:n关系:
players.id
-> bans.player
并命名为bans__fk_player
servers.id
-> bans.server
并命名为bans__fk_server
答案 0 :(得分:1)
1)SO人员已经对此进行了评论:您需要在外键定义中删除标识符周围的引号。有关在mysql / MariaDB中使用引号的一般性讨论,另请参见this SO post。
2)另一个问题是您没有正确定义约束,它缺少外键的名称。语法如下,如this mysql turorial中所述:
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
因此您的代码应为:
...
constraint bans__player
foreign key bans__fk_player (player) references players (id),
constraint bans__server
foreign key bans__fk_server (server) references servers (id)
...
请参见this db fiddle。
这也应该工作,并且产生较短的语法(您可能不需要显式地命名约束):
...
foreign key bans__fk_player (player) references players (id),
foreign key bans__fk_server (server) references servers (id)
...
如果仍然遇到错误,则必须查看引用表(服务器和播放器)的定义。在两个表中,id必须是表的主键,或者必须由唯一约束控制。当然,它必须是数字。
答案 1 :(得分:0)
如果您想引用列id
,在MariaDB(同样在MySQL)中,您应使用“回勾”,如:
create table bans
(
id int auto_increment primary key ,
reason int not null,
player int not null,
server int not null,
starts timestamp default current_timestamp not null,
ends DATETIME not null,
constraint bans__fk_player
foreign key (player) references players (`id`),
constraint bans__fk_server
foreign key (server) references servers (`id`)
);