views:

78

answers:

0

With a data structure like this:

Tags {id, lft, rgt, depth, parentid}
ObjectTags {id, tag_id, object_id}
Objects {id}

(the entries in Tags are organized as nested sets)

I need a result that contains the Tag.id and the number of relationships that this Tag holds, including the relations of it's children but without duplicates.

Example:
Tags contains this tree:

Vehicles
  |-- motorised
  |     |-- 4 wheels
  |     |-- 2 wheels
  |
  |-- not motorised
  |     |-- 4 wheels
  |     |-- 2 wheels
  |
  |-- color
        |-- green
        |-- red

Objects contains "Bike", "Toyota Prius", "BMW Dakar"
and ObjectTags contains this relationships:

  • "Bike" -> ("not motorised--2 wheels", "green")
  • "Toyota Prius" -> ("motorised--4 wheels", "green")
  • "BMW Dakar" -> ("motorised--2 wheels", "red")

The resultset should then count the relations like this:

Vehicles (3)
  |-- motorised (2)
  |     |-- 4 wheels (1)
  |     |-- 2 wheels (1)
  |
  |-- not motorised (1)
  |     |-- 4 wheels
  |     |-- 2 wheels (1)
  |
  |-- color (3)
        |-- green (2)
        |-- red (1)

I have this query that gives me the result in SqlServer 2008:

SELECT t.Id As TagId,
    (SELECT COUNT(DISTINCT ft.fileid) AS DistIds
    FROM ObjectTags AS ft 
    LEFT OUTER JOIN Tags AS t2 ON t2.id = ft.tagid 
    WHERE (t2.lft >= 
            (SELECT tmp1.lft FROM Tags tmp1 WHERE tmp1.Id = t.Id)
    AND (t2.rgt <= 
            (SELECT tmp1.rgt FROM Tags tmp1 WHERE tmp1.Id = t.Id) ))
    ) As TagFileCount
FROM Tags AS t ORDER BY t.Id

Unfortunately this doesn't work in SqlServerCE, because it doesn't allow nested selects.
Can someone help me with this query? If you can optimise my existing query as well, please tell me because I wouldn't count SQL to my strengths :-)