检查递归外键的方法

发布于 2024-11-09 19:08:38 字数 521 浏览 5 评论 0原文

假设我有一个名为 EMPLOYEE 的表,该表有一个名为 ManagerID 的字段。该字段是 EMPLOYEE 表中另一条记录(其经理是谁)的 FK。验证不存在循环引用(递归外键)的理想方法是什么?

编辑 - 让我补充一下,每个员工并不需要经理。将会有一些员工记录未设置其 ManagerID 字段。

*示例:用户 123 将用户 345 作为其经理。用户 345 有用户 567 作为其经理。由于某些疯狂的原因,用户 567 将用户 123 作为其管理员。

我想检查用户 345 是否处于循环引用中。*

解决此问题的最佳方法是什么?一个简单的查询?业务逻辑代码(C#/VB.NET)?

其他人做了什么?

示例表架构 -

-- Employee Table --
UserID (int - PK)
ManagerID (int - FK to another UserID; can be null)

Say I have a table named EMPLOYEE, and the table has a field called ManagerID. This field is a FK to another record of the EMPLOYEE table of who their manager is. What is an ideal way to verify that there is no circular reference (recursive foreign keys)?

EDIT - Let me add that every employee does NOT need a manager. There will be some employee records that do not have their ManagerID field set.

*Example: User 123 has User 345 as their manager. User 345 has User 567 as their manager. For some crazy reason, User 567 has User 123 as their manager.

I want to check if User 345 is in a circular reference.*

What is the best way to figure this out? A simple query? Business logic code (C#/VB.NET)?

What have other people done?

Example table schema -

-- Employee Table --
UserID (int - PK)
ManagerID (int - FK to another UserID; can be null)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谎言月老 2024-11-16 19:08:38

如果您正在使用 SQL Server,这里是符合您要求的解决方案;
需要编写CTE来查找循环引用;

下面的查询将为您提供具有循环引用的用户 ID

WITH TRACKER AS
(


SELECT U.id,U.manager_id,CAST(','+cast(U.id as varchar(36))+',' as varchar(max)) as Path,0 as Cycle FROM User_table AS U
    UNION ALL
    SELECT U.id,U.manager_id, TRACKER.Path + CAST(U.id AS varchar(36))+',', case WHEN TRACKER.Path LIKE '%,'+CAST(U.id AS VARCHAR(36)) + ',%' then 1 else 0 end   FROM User_table AS U

 INNER JOIN TRACKER ON U.manager_id = TRACKER.id WHERE TRACKER.Cycle=0 
)

SELECT TRACKER.id from TRACKER where Cycle= 1;

If you are dealing with SQL server, here is the solution that matches your requirement;
You need to write CTE to find cyclic references;

Below query will give you user IDs having cyclic reference

WITH TRACKER AS
(


SELECT U.id,U.manager_id,CAST(','+cast(U.id as varchar(36))+',' as varchar(max)) as Path,0 as Cycle FROM User_table AS U
    UNION ALL
    SELECT U.id,U.manager_id, TRACKER.Path + CAST(U.id AS varchar(36))+',', case WHEN TRACKER.Path LIKE '%,'+CAST(U.id AS VARCHAR(36)) + ',%' then 1 else 0 end   FROM User_table AS U

 INNER JOIN TRACKER ON U.manager_id = TRACKER.id WHERE TRACKER.Cycle=0 
)

SELECT TRACKER.id from TRACKER where Cycle= 1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文