SQL Query在单个表中查找链接记录

时间:2013-11-12 19:27:20

标签: sql

我的表格如下所示:

ID   Customer Name   LinkedID
1    A        X      
2    B        Y      1
3    C        Z      2

我需要编写一个查询:

1- For each ID (1,2,3)
2- If there is a LINKEDID defined (2,3 have links)
3- If the CUSTOMER of the LINKEDID is A
4- Return record for that ID

所以在上面的例子中它会做类似的事情:

  • ID 2,3的指定了LinkedID
  • ID2链接到#1,即客户A(好)返回ID2
  • ID3链接到#2,即客户B(坏)

所以最终的结果是ID2。

SELECT * FROM TABLE WHERE LINKED <> NULL    // this will get me the list
? But now how do I iterate over each of the results and compare the customers?

非常感谢任何帮助。 谢谢,

2 个答案:

答案 0 :(得分:1)

select t1.id
from your_table t1
inner join your_table t2 on t1.linkedid = t2.id
where t2.customer = 'A'

答案 1 :(得分:1)

两次加入桌面。 C是主表,P表示由linkedID引用的父表。

SELECT  *
FROM    CustomerTable C
JOIN    CustomerTable P ON P.ID = C.LinkedID
WHERE   P.Customer = 'A'