【发布时间】:2018-05-01 23:02:18
【问题描述】:
我正在学习有关 SQL 的 UDEMY 课程。讲师正在使用postgresql。我在 MySQL 工作台工作。我们的企业开发是在 AWS 平台上使用 MySQL 5.6。所以我想学习MySQL。
有一个关于“创建表”和使用约束和外键命令来链接两个不同表中的主键的讲座。这是我想用我的数据做的事情,所以挑战是相关的。讲师的代码无法为我编译。我收到“错误代码 1215。无法添加外键约束”。
我在这里读到变量必须具有完全相同的定义。因此,我将讲师的表格从“串行”更改为 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 blah blah 的查询 - 请参阅stackoverflow.com/questions/10028214/… 或类似内容。基本上,尝试在代码中的 CONSTRAINT 一词之前添加
ALTER TABLE blah ADD。确保在外键中引用的列被索引
标签: mysql postgresql