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'。确保在外键引用的列被索引 –