Question

I have some database schema where I have two tables and a map table to define a relationship between my two tables. The tables are a user table (which for this example I've called Sibling) and an object table where the map table defines what objects the users are related to. Of course I can easily run a query to get a list of the map table's records by user ID but I also need to get all of the "sibling" records of other users who may be related to the same objects. I've tried using a common table expression to query the records but I'm running into an infinite loop problem. I'm not even sure if a CTE is the way I should be going about this problem. I have set up a SQLFiddle example here.

http://sqlfiddle.com/#!6/289a4/6

So if I query on a sibling ID of 101 I would like to get following set of records.

1 101

1 102

2 101

2 103

Était-ce utile?

La solution

Required output:

declare @Sibling int 
set @Sibling = 101

;with Objects as 
(
      select ObjectId from ObjectSiblingMap 
      where SiblingId = @Sibling
)
,Siblings as 
(
      select ObjectId,SiblingId from ObjectSiblingMap
      where ObjectId in 
      (select ObjectId from Objects)
)
select * from Siblings

Autres conseils

You can retrieve the objects mapped to a specific user easily:

SELECT ObjectId
FROM ObjectSiblingMap
WHERE SiblingId = 101

Now, to get the users who are related to the same objects as the user 101, you shall use a nested query based on the previous result:

SELECT SiblingId
FROM ObjectSiblingMap
WHERE SiblingId <> 101
    AND ObjectId IN
    (SELECT ObjectId
    FROM ObjectSiblingMap
    WHERE SiblingId = 101)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top