[英]MySQL MariaDB wont create Table with a foreign key
I'm having a problem with my SQL Tables. 我的SQL表有问题。 So I have my Usertable: 所以我有我的用法:
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(50) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`)
) ;
This table already exists and was created without any problems. 此表已存在且创建没有任何问题。 I Want to create a score Table like this: 我想创建一个这样的得分表:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (NICKNAME) REFERENCES USER(Nickname)
)
On execution of the query I get this errormassage: 在执行查询时,我得到了这个errormassage:
**#1005 - Kann Tabelle `xxxxx`.`scores` nicht erzeugen (Fehler: 150 "Foreign key constraint is incorrectly formed") (Details…)**
Its in German and says cant create Table, Error 150, I cant see where the key constraint is wrong, I used the same syntax in postgreSQL and it worked fine, but somehow MySQL is not accepting it. 它用德语说不能创建Table,Error 150,我无法看到键约束错误的地方,我在postgreSQL中使用了相同的语法并且它工作正常,但不知何故MySQL不接受它。 Any Ideas? 有任何想法吗?
That is strange. 这很奇怪。 If nickname
is indeed the primary key, then your code should work. 如果nickname
确实是主键,那么您的代码应该可行。
It is much more nature, though, to use the auto-incremented column as the primary key. 但是,使用自动递增列作为主键更加自然。 If you want the nickname, then use a join when you query. 如果您想要昵称,请在查询时使用连接。
So: 所以:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
UserId int(11) NOT NULL,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (UserId) REFERENCES USER(Id)
);
user - is a keyword. user - 是一个关键字。
It may be a good idea to use another table name eg "tblUser", or use quotes again `` 使用另一个表名称(例如“tblUser”)或再次使用引号``可能是个好主意
FOREIGN KEY (NICKNAME) REFERENCES `USER`(ID)
Thanks to Mr. Gordon Linoff I was able to find my Mistake: 感谢Gordon Linoff先生,我找到了错误:
I had to declare NICKNAME to be declared UNIQUE, only then the FOREIGN KEY constraint could be added to other tables 我必须声明NICKNAME被声明为UNIQUE,然后才能将FOREIGN KEY约束添加到其他表中
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`),
UNIQUE KEY `NICKNAME` (`NICKNAME`)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.