2
我正在關注一個關於SQL的UDEMY課程。教師正在使用postgresql。我在MySQL工作臺上工作。我們的企業發展是在AWS平臺上的MySQL 5.6中進行的。所以我想在MySQL中學習。MYSQL創建表,約束,外鍵
有關於「創建表」和使用約束和外鍵命令鏈接兩個不同表中的主鍵的講座。這是我想要處理的數據,所以挑戰是相關的。教練的代碼不會爲我編譯。我得到「錯誤代碼1215.無法添加外鍵約束」。
我在這裏讀到變量必須有完全相同的定義。於是我把教師的表從「serial」改爲int。我仍然收到錯誤。我試圖簡化代碼。我還沒有到達任何地方。任何人都可以幫助我理解它爲什麼不執行?
create table if not exists accounts(
user_id INT auto_increment not null,
username varchar(50) unique not null,
password varchar(50) not null,
email varchar(350) unique not null,
created_on timestamp not null,
last_login timestamp,
primary key (user_id)
);
create table if not exists role(
role_id INT auto_increment not null,
role_name varchar(250) unique not null,
PRIMARY KEY (role_id)
);
create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),
constraint accounts_role_role_id_fkey foreign key (role_id)
references role(role_id) match simple
on update no action
on delete no action,
constraint accounts_role_user_id_fkey foreign key (user_id)
references account (user_id) MATCH SIMPLE
on update no action
on delete no action
);
能否請編輯您的帖子,選擇所有的SQL代碼,然後按{}文本框上方的按鈕將其格式化爲代碼。我會爲你做,但這個按鈕不會顯示在iPhone上:( –
我主要與其他品牌的數據庫一起工作,但添加外鍵的語法看起來像缺少一些關鍵字。要添加一個fk到現有的表,你需要發出一個查詢看起來更像ALTER TABLE blah ADD CONSTRAINT constraintname FOREIGN KEY等等 - 看到https://stackoverflow.com/questions/10028214/add-foreign-key-to-existingtable或類似。基本上,試着在你的代碼中的CONSTRAINT之前添加'ALTER TABLE blah ADD'。確保在外鍵引用的列被索引 –