设计数据库表以在允许插入之前检查另一个表中的ID
我确信这是一个非常简单的数据库问题,但我什至不知道要谷歌什么,所以希望有人可以在这里帮助我。
我正在尝试创建两个互连的表。例如,假设我有一个包含员工姓名和员工 id 的员工表,然后我正在创建另一个表,employee_bonus,其中包含员工 id 和奖金金额。我想要的是,每次插入行时,employee_bonus 表都会自动检查员工表,以确保员工 ID 存在于员工表中,如果不存在则拒绝插入。问题是,一名员工可能有多项奖金,所以我只想检查它是否存在,而不是一对一。这有道理吗?这可能吗?我该怎么做,那叫什么?
另外,我正在 MySql 中执行此操作。
I've got what I'm sure is a really simple database question, but I don't even know what to google, so hopefully someone can help me here.
I'm trying to create 2 tables that are interconnected. For example, lets say I have an employee table with employee name and employee id, then I'm creating another table, employee_bonus, with employee id and bonus amount. What I want is for the employee_bonus table to automatically check with the employee table every time a row is inserted to make sure that the employee id exists in the employee table and reject the insert if not. The thing is, there could be multiple bonuses for a single employee, so I just want it to check that it exists, not make it one to one. Does that make sense? Is that possible? How would I do that and WHAT is that called?
Also, I'm doing this in MySql.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自维基百科:外键
在关系数据库的上下文中,外键是两个表之间的引用约束。
http://en.wikipedia.org/wiki/Foreign_key
From wikipedia: Foreign Key
In the context of relational databases, a foreign key is a referential constraint between two tables.
http://en.wikipedia.org/wiki/Foreign_key
以下是您正在寻找的内容的基本示例:
The following is a basic example of what you are looking for:
由于它不是一对一的关系,因此为employee_bonus 表提供自己的主键,并在employee 表的id 列和employee_bonus 表中的employee_id 之间建立外键关系。
Since it's not a 1-to-1 relationship give the employee_bonus table its own primary key and establish a foreign key relationship between the employee table's id column and the employee_id in the employee_bonus table.
如果您想在尝试添加缺失的员工时避免插入错误,请尝试以下操作:
如果该员工存在,则将插入一行,如果不存在,则不执行任何操作。
If you want to avoid an error on insertion when attempting to add a missing employee, try this:
This will insert one row if the employee exists and will do nothing if it doesn't.