简单的递归查询

时间:2010-02-23 21:26:31

标签: sql-server sql-server-2005 tsql

我有2个表如下(显示的样本数据):

TableName: A
ID              Type
1  Bug
2  Requirement
3  Task
4  Specification
5  Bug
6  Specification
7  Production Issue
8  Production Issue
9  Bug
10          Task

Tablename: B
ID  RelatedID
1  2
1  7
5  8
5  4
9  6
9  10

我想获取所有至少存在一个相关生产问题的错误或没有相关生产问题的错误。

预期输出将如下所示(因为这些是至少有一个相关生产问题的错误)

output
1
5

1 个答案:

答案 0 :(得分:1)

别名是去这里的方式

SELECT pri.Type AS 'Primary Type', rel.Type AS 'Related Type' 
FROM A AS pri 
   INNER JOIN B ON B.ID = pri.ID
   INNER JOIN A AS rel ON B.RelatedID = rel.ID
WHERE pri.Type = 'Bug' AND rel.Type = 'Production Issue;