[英]Using two foreign keys as a primary key - MySQL
我是MySQL的新手(必須為uni學習它)。 我必須為作業創建數據庫和Web界面。
在其中一個表上,我有兩列,這兩列都是外鍵,我需要將它們用作主鍵。
這是到目前為止的代碼:
drop database if exists testJoke;
create database testJoke;
use testJoke;
CREATE TABLE Author
(
id int(11) NOT NULL ,
name varchar(255) NULL ,
cust_email varchar(255) NULL,
password char(32) null,
PRIMARY KEY (id)
);
**CREATE TABLE AuthorRole
(
authorid int(11) NOT NULL ,
roleid varchar(255) NOT NULL,
PRIMARY KEY (authorid, roleid),
FOREIGN KEY(authorid) REFERENCES Author(id),
FOREIGN KEY(roleid) REFERENCES Role(id)
);**
CREATE TABLE Category
(
id int(11) NOT NULL ,
name varchar(255) NULL,
PRIMARY KEY (id)
);
CREATE TABLE Joke
(
id int(11) NOT NULL ,
joketext text NULL ,
jokedate date NOT NULL ,
authorid int(11) NULL,
PRIMARY KEY (id),
FOREIGN KEY(authorid) REFERENCES Author(id)
);
CREATE TABLE JokeCategory
(
jokeid int(11) NOT NULL ,
categoryid int(11) NOT NULL ,
PRIMARY KEY (jokeid, categoryid),
FOREIGN KEY(jokeid) REFERENCES Joke(id),
FOREIGN KEY(categoryid) REFERENCES Category(id)**
);
CREATE TABLE Role
(
id varchar(255) NOT NULL ,
description varchar(255) NULL ,
PRIMARY KEY (id)
);
所有表語法都與提供的數據字典一致。
當我在mysql命令行中運行它時,我在上面以粗體突出顯示的部分(表“AuthorRole”)上出現錯誤,說它“無法添加外鍵約束”。
我試過調試它,它似乎是:
FOREIGN KEY(roleid) REFERENCES Role(id)
導致問題的外鍵(如果我刪除它,一切正常,如果我留下並刪除其他外鍵,則會出錯)。
如果有人可以解釋我哪里出錯了,我將非常感激。
我試過谷歌搜索,但無法找到任何東西(可能是因為我使用了錯誤的關鍵字)。
謝謝
干杯科里
首先創建表“Role”,然后創建表“AuthorRole”,它就可以了
CREATE TABLE Role
(
id varchar(255) NOT NULL ,
description varchar(255) NULL ,
PRIMARY KEY (id)
);
CREATE TABLE AuthorRole
(
authorid int(11) NOT NULL ,
roleid varchar(255) NOT NULL,
PRIMARY KEY (authorid, roleid),
FOREIGN KEY(authorid) REFERENCES Author(id),
FOREIGN KEY(roleid) REFERENCES Role(id)
);
在創建主鍵時,最好使用id INT(11) NOT NULL AUTO_INCREMENT
這只是因為您指的是表引用時未創建的表的主鍵,請嘗試以下sql腳本:
drop database if exists testJoke;
create database testJoke;
use testJoke;
CREATE TABLE Author
(
id int(11) NOT NULL ,
name varchar(255) NULL ,
cust_email varchar(255) NULL,
password char(32) null,
PRIMARY KEY (id)
);
CREATE TABLE Role
(
id varchar(255) NOT NULL ,
description varchar(255) NULL ,
PRIMARY KEY (id)
);
CREATE TABLE AuthorRole
(
authorid int(11) NOT NULL ,
roleid varchar(255) NOT NULL,
PRIMARY KEY (authorid, roleid),
FOREIGN KEY(authorid) REFERENCES Author(id),
FOREIGN KEY(roleid) REFERENCES Role(id)
);
CREATE TABLE Category
(
id int(11) NOT NULL ,
name varchar(255) NULL,
PRIMARY KEY (id)
);
CREATE TABLE Joke
(
id int(11) NOT NULL ,
joketext text NULL ,
jokedate date NOT NULL ,
authorid int(11) NULL,
PRIMARY KEY (id),
FOREIGN KEY(authorid) REFERENCES Author(id)
);
CREATE TABLE JokeCategory
(
jokeid int(11) NOT NULL ,
categoryid int(11) NOT NULL ,
PRIMARY KEY (jokeid, categoryid),
FOREIGN KEY(jokeid) REFERENCES Joke(id),
FOREIGN KEY(categoryid) REFERENCES Category(id)
);
首先創建表Role,然后創建AuthorRole。
嘗試改變
roleid varchar(255) NOT NULL,
至
roleid int(11) NOT NULL,
因為字段和關鍵字段屬於不同類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.