sql检查2列中的逻辑错误
假设我有一个仅包含 2 列的 employee
表:
- employee_id
- manager_id
添加到此表的所有员工都会有一个附带的 manager_id
,它实际上是一个 employee_id
已经存在(除了一个,首席执行官可能没有经理,但这并不重要)。
如果 A
是 B
的管理器,我们如何强制执行检查,以便 A 的管理器可以采用除 B
之外的任何值,从而导致违反商业规则?
Assuming I have an employee
table with 2 columns only:
- employee_id
- manager_id
All employees added to this table would have an accompanying manager_id
that is actually an employee_id
that already exists (save for one, the CEO probably doesn't have a manager, but that's not important).
If A
is the manager of B
, how do we enforce a check such that A's manager can take any value BUT B
, thus resulting in a violation of the business rule?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说最好的方法是在插入表时创建一个触发器,该触发器将简单地检查
manager_id NOT IN(从员工中选择employee_id,其中manager_id = %insertid%)
。I'd say the best way would be to create a TRIGGER on the insert into the table that would simply check that
manager_id NOT IN (SELECT employee_id from employee where manager_id = %insertid%)
.答案的一半是外键:manager_id引用employee(employee_id)
另一半是检查约束,manager_id<>employee_id
Half of the answer is a foreign key: manager_id references employee(employee_id)
The other half is a check constraint, manager_id<>employee_id
问题比这更深入,您希望避免图中出现任何循环,从而使其有效成为一树。
我认为你最好在应用程序级别这样做。
更新:但如果您更喜欢使用触发器来执行此操作,请查看公用表表达式 (CTE)。您可以在检查循环的触发器中创建递归查询:
注意:假设
employee_id
是主键,manager_id
是外键键指向employee.employee_id
。The problem goes deeper than that, you want to avoid any cycles in your graph, making it effectively a tree.
I think you're better off doing that at the application level.
UPDATE: But if you prefer to do it with a trigger, take a look at common table expressions (CTEs). You can create a recursive query in a trigger that checks for cycles:
Note: it's assumed that
employee_id
is a primary key andmanager_id
is a foreign key pointing back toemployee.employee_id
.