简体   繁体   中英

SQL 2008 R2 Recursive Query

I have the following SQLtable

[rel_id] [int] NOT NULL,
[rel_type_id] [int] NOT NULL,
[left_object_id] [int] NOT NULL,
[left_object_type] [int] NOT NULL,
[right_object_id] [int] NOT NULL,
[right_object_type] [int] NOT NULL,
[template] [char](1) NOT NULL

Basically this table controls relationships between different objects. I' need to construct some SQL that given left_object_id can work out recursively all the objects that has relationships to it.

I'm only interested in object where both the left & right object types are 5

In simple terms the SQL would need to do the following 1. Input a left object id 2. Search the table and return all right object ids where associated left object matches the input 3. For each of the right object id found go back repeat from step 1 4. Repeat until no further values are found

Sounds complex, but I'm sure there is some SQL guru out there who can solve this.

Many Thanks.

It's difficult without test data but something like this should do the trick:

I assume a tree, having one parent element left side and a children list right side. This query should come back with entries having their parent of type 5 and at least one child of type 5.

SELECT *
FROM @tbl AS tbl
WHERE (SELECT leftObj.rel_type_id FROM @tbl AS leftObj WHERE leftObj.right_object_id=tbl.rel_id)=5
  AND EXISTS(SELECT rightObjList.rel_type_id 
             FROM @tbl AS rightObjList 
             WHERE rightObjList.left_object_id=tbl.rel_id
               AND rightObjList.rel_type_id=5)

 <table><tbody><tr><th>rel_id</th><th>rel_type_id</th><th>left_object_id</th><th>left_object_type</th><th>right_object_id</th><th>right_object_type</th></tr><tr><td>52</td><td>44</td><td>4</td><td>5</td><td>1</td><td>5</td></tr><tr><td>53</td><td>44</td><td>4</td><td>5</td><td>3</td><td>5</td></tr><tr><td>54</td><td>44</td><td>5</td><td>5</td><td>4</td><td>5</td></tr><tr><td>55</td><td>44</td><td>5</td><td>5</td><td>6</td><td>5</td></tr></tbody></table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM