我想使用两个表," employee_expenses"和" expense_master"记录并输出所有员工费用。我怎么能用外键做到这一点?
employee_expense列:Employee_ID(PK)
expense_master列:员工(FK到Employee_ID),expense_ID(PK)日期,描述,费用金额
描述栏有四种可能的输入,从下拉菜单(住宿,食物,旅行,其他)中选择。因此,expense_master表中的expense_ID(PK)只有四个值 - " 1,2,3,4"
我希望能够像这样输出一个特定员工的所有费用清单,以便每位员工从他的账户中查看:
请告诉我该怎么做,即从这里采取的关于上述两个表的数据库行动,以实现这一目标,谢谢。
答案 0 :(得分:1)
嗯,你反复问过很多(包括与肖恩聊天)。所以我会分享这个。有时我们只需要接受这个人不知道该怎么做,并且任何帮助的指针都不起作用或理解。所以请问下面的内容。
drop table if exists employees;
create table employees
( empId int auto_increment primary key,
name varchar(100) not null
);
drop table if exists expenses;
create table expenses
( expId int auto_increment primary key,
category varchar(50) not null, -- maybe this goes to its own FK
amount decimal(12,2) not null,
empId int not null,
dtOccurred datetime not null, -- or just a `Date` datatype
constraint `fk_exp_emp001` foreign key (empId) references employees(empId),
key `key_exps_empid` (empId) -- maybe even a composite index: key(empId,dtOccurred)
);
<强>测试强>
insert expenses(category,amount,empId,dtOccurred) values ('fishing supplies',100,10,'2009-01-30');
-- above line, Error 1452: FK violation. Emp 10 does not exist
insert employees(name) values ('Jim Smith'); -- id 1
select last_insert_id(); -- returns 1
insert expenses(category,amount,empId,dtOccurred) values ('fishing supplies',100,1,'2009-01-30');
-- above inserts fine
请参阅This Answer的后续部分以了解级联删除。 MySQL手册页面也标题为Using FOREIGN KEY Constraints