分层SQL查询
我有一个自引用表(客户)和一个将链接到该表(公司)中的一条记录的表,即
Customers Companies
********* *********
ID ID
ManagerID --> DirectorID
ManagerID 引用客户表中的另一条记录。
我需要执行一个查询,通过给定特定的客户 ID,它将找到客户所属的公司。如果我在 C# 中执行此操作,它将看起来像这样(这是示例代码,不是功能性的):
public static Company FindCompany(Customer customer)
{
while (customer.ManagerID != null)
{
customer = customer.GetManager();
}
return Company.FindByDirector(customer.ID);
}
因此有 2 个步骤:
1) 遍历 Customer 表(通过 ManagerID),直到找到没有 ManagerID 的 Customer。 (董事)
2) 找到与该客户相关的公司。
有人可以帮我吗?
谢谢。
I have a self-referencing table (Customers) and a table that will link to one record in that table (Companies) i.e.
Customers Companies
********* *********
ID ID
ManagerID --> DirectorID
ManagerID refers to another record in the Customer table.
I need to perform a query where by given a specific customer ID, it will find the Company that customer belongs to. If I was to do this in C# it would look something like (this is sample code, not functional):
public static Company FindCompany(Customer customer)
{
while (customer.ManagerID != null)
{
customer = customer.GetManager();
}
return Company.FindByDirector(customer.ID);
}
So there are 2 steps:
1) Traverse up the Customer table (via ManagerID) until we find a Customer with no ManagerID. (The Director)
2) Find the Company relating to that Customer.
Can anyone help me out?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西,虽然未经测试。
基于 CTE 使用公用表表达式的递归查询
Something like this, untested though.
Based on CTEs Recursive Queries Using Common Table Expressions