使用触发器的约束
我使用三个表 - 订单、员工和职位。 Orders 有 Employee_no,Employee 表有 Position_no。我想确保订单表中的 Employee_Nos 是销售部门的员工编号。 Sales 中员工的 Position_no 为 3, 4, 5, 6。我使用查询 1(见下文)添加检查约束。但是,它不喜欢子查询。我可以使用查询 2(见下文),它确保 Orders 表中的 Employee_No 在列表中(该列表是销售员工的员工编号)。但是,如果有新员工加入,查询 2 将不起作用。我知道可以使用触发器解决这个问题,但不知道如何解决。如果有人能帮助我,我会很高兴。
I am using three tables - Orders, Employee and Position. Orders has Employee_no, and Employee table has Position_no. I want to make sure that the Employee_Nos in Order table are the numbers of those employee who are in Sales. The Position_no of employees in Sales are 3, 4, 5, 6. I used Query 1 (see below) to add a check constraint. However, it doesn't like the subquery. I could use Query 2 (see below) which makes sure that the Employee_No in Orders table is in the list (the list is the employee nos of employees who are in sales). However, Query 2 wouldn't work if a new employee joins. I know this could be solved using a trigger, but not sure how. Would be glad if somebody could help me out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在你的情况下我不会使用触发器。它们很难处理,您需要知道如何正确管理它们。
考虑以下解决方案。
我现在没有 Oracle 来测试我的解决方案,但我想您已经明白了。您在
check_sales
中选择了不正确的订单,并添加了一个约束,要求其为空。I wouldn't use triggers in your case. They are difficult to deal with and you need to know how to manage them correctly.
Consider the following solution.
I don't have the Oracle now to test my solution, but I think you got the idea. You select incorrect orders into
check_sales
and add a constraint that it should be empty.啊,类型和子类型。
销售员工是 EMP 的一个子类型。假设 EMP 主键是 EMP_ID。
您可以在 EMP 中创建一个新列 SALES_EMP_ID 和一个检查约束,以便仅在 SALES 中存在员工的地方设置它,并且如果设置,它必须等于 EMP_ID。还有另一个强制唯一性的约束。
然后您可以创建从 ORDERS 到 EMP.SALES_EMP_ID 的引用完整性约束
请参阅以下演示。只有前两次插入 T_EMP 会成功 - 其他测试检查约束。在 T_ORDERS 的插入中,只有第一个(推销员)会成功。
Ah, types and subtypes.
A SALES employee is a subtype of EMP. Assume the EMP primary key is EMP_ID.
You can create a new column SALES_EMP_ID in EMP and a check constraint so that it is only set where there employee is in SALES and that, if set, it must be equal to EMP_ID. And another constraint to enforce uniqueness.
Then you can create a referential integrity constraint from ORDERS to EMP.SALES_EMP_ID
See the following demo. Only the first two inserts into T_EMP will succeed - the others test the check constraints. Of the inserts into T_ORDERS, only the first (salesman) will succeed.
我不经常做触发器,但基本上是这样的。我的语法可能不太正确。
I don't do triggers often but it would basically be like this. I might have the syntax not quite right.