关于MYSQL数据库的外键问题

十歌 2018-08-08 08:16:28
create table employee(
e_no int(11) primary key not null unique,
e_name varchar(50) not null,
e_gender char(2),
dept_no int(11) not null,
e_job varchar(50) not null,
e_salary int(11) not null,
hireDate date not null
);

create table dept(
d_no int(11) primary key auto_increment not null unique,
d_name varchar(50) not null,
d_location varchar(100),
constraint fk_dept foreign key(d_no) references employee(dept_no)
);

报错:
Error Code : 1005
Can't create table '.\qly\dept.frm' (errno: 150)
(0 ms taken)

看网上分析 应该是外键问题 但应该不是数据类型的问题啊 都是int(11) 是因为在主表中的dept_no字段没有unique的原因吗?
请教各位
...全文
85 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
吉普赛的歌 版主 2018-08-08
  • 打赏
  • 举报
回复
引用 2 楼 q631890839 的回复:
[quote=引用 1 楼 yenange 的回复:]
你外键设置反了。
先有了部门, 员工表才可能有部门编号。

# 先创建部门表
create table dept(
d_no int(11) primary key auto_increment not null unique,
d_name varchar(50) not null,
d_location varchar(100)
);

# 再创建员工表,dept_no 是外键, 与 部分门表关联
create table employee(
e_no int(11) primary key not null unique,
e_name varchar(50) not null,
e_gender char(2),
dept_no int(11) not null,
e_job varchar(50) not null,
e_salary int(11) not null,
hireDate date not null,
constraint fk_employee foreign key(dept_no) references dept(d_no)
);


另外, 在生产环境中, 一般不需要显式设置外键, 心里知道有关联就行了。
这样会少很多麻烦, 实际效率也会比有显式外键高。


非常感谢,原来是先后的原因
这样说来 外键不会因为两个字段的 not null 和 unique约束的不匹配 而导致无法建立[/quote]
嗯, 没事就结贴吧。
十歌 2018-08-08
  • 打赏
  • 举报
回复
引用 1 楼 yenange 的回复:
你外键设置反了。
先有了部门, 员工表才可能有部门编号。

# 先创建部门表
create table dept(
d_no int(11) primary key auto_increment not null unique,
d_name varchar(50) not null,
d_location varchar(100)
);

# 再创建员工表,dept_no 是外键, 与 部分门表关联
create table employee(
e_no int(11) primary key not null unique,
e_name varchar(50) not null,
e_gender char(2),
dept_no int(11) not null,
e_job varchar(50) not null,
e_salary int(11) not null,
hireDate date not null,
constraint fk_employee foreign key(dept_no) references dept(d_no)
);


另外, 在生产环境中, 一般不需要显式设置外键, 心里知道有关联就行了。
这样会少很多麻烦, 实际效率也会比有显式外键高。


非常感谢,原来是先后的原因
这样说来 外键不会因为两个字段的 not null 和 unique约束的不匹配 而导致无法建立
吉普赛的歌 版主 2018-08-08
  • 打赏
  • 举报
回复
你外键设置反了。
先有了部门, 员工表才可能有部门编号。

# 先创建部门表
create table dept(
d_no int(11) primary key auto_increment not null unique,
d_name varchar(50) not null,
d_location varchar(100)
);

# 再创建员工表,dept_no 是外键, 与 部分门表关联
create table employee(
e_no int(11) primary key not null unique,
e_name varchar(50) not null,
e_gender char(2),
dept_no int(11) not null,
e_job varchar(50) not null,
e_salary int(11) not null,
hireDate date not null,
constraint fk_employee foreign key(dept_no) references dept(d_no)
);


另外, 在生产环境中, 一般不需要显式设置外键, 心里知道有关联就行了。
这样会少很多麻烦, 实际效率也会比有显式外键高。

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧