Toon posts:

[MSSQL] N:N query

Pagina: 1
Acties:

Verwijderd

Topicstarter
Ik heb een simpele database

tabel1 menu
code:
1
id  |  title  |  url


tabel2 relatie
code:
1
id  |  parentID  |  childID  |  volgnr

De werking laat zich wel raden... hiermee kan dus een oneindige tree mee worden opgebouwd. Over het algemeen zit er maximaal een diepte van 4 in de tree...

Op dit moment wordt alles dmv query's in een recursieve functie opgehaalt, werkt prima, maar lijkt mij een beetje overload te geven. Daarnaast draait dit in een multi-user omgeving en zal behoorlijk wat keren opgevraagd worden. Mijn idee was dus om dit binnen enkele query's op te lossen. Ik ben alleen bang dat het niet helemaal haalbaar is, omdat als je het eerste niveau ophaalt je deze resultaten ook weer nodig hebt om de onderliggende niveau's te bepalen.

Mijn vraag: Heeft iemand dit vaker gedaan met zo'n db-model (ongetwijfeld) en kan mij een stukje de juiste richting in duwen?

Niet schokkend, maar zal maar wel mn query plaatsen die ik gebruik om het rootmenu te bepalen

code:
1
2
3
SELECT titel FROM NavMenus
    INNER JOIN navRelaties ON navMenus.ID = ChildID 
    WHERE parentID = 1

In weze is het rootmenu wat ik hierboven ophaal niet echt het rootmenu, er zit nog een niveau boven wat één item bevat omdat de twee tabellen gebruikt worden voor meerdere sites

Overigens: het db model aanpassen zal niet gaan, dan moet ik nml heel veel andere dingen gaan aanpassen in de rest van de software en daar heb ik geen zin in/tijd voor :)

  • whoami
  • Registratie: December 2000
  • Laatst online: 17:38
Je kan het zo doen:
code:
1
2
3
SELECT * 
FROM navMenus Parent, navMenus Child
WHERE Child.ParentId = Parent.id

https://fgheysels.github.io/


Verwijderd

Topicstarter
Dat gaat niet aangezien je in feite eerst je root id moet opgeven. Dit is het id uit de tabel navMenus, in feite is dit een record die niet binnen het menu te zien is, maar het alleen mogelijk maakt om voor meedere sites binnen dezelfde twee tabellen een treemenu te bouwen...

  • Janoz
  • Registratie: Oktober 2000
  • Laatst online: 17-08 23:56

Janoz

Moderator Devschuur®

!litemod

whoami schreef op 22 October 2003 @ 15:45:
Je kan het zo doen:
code:
1
2
3
SELECT * 
FROM navMenus Parent, navMenus Child
WHERE Child.ParentId = Parent.id


Dan heb je maar 1 niveau en niet oneindig. Oneindig is nogal lastig te doen met sql (Lees niet). Je zou kunnen overwegen de gegevens pas op te halen waneer deze worden gevraagd. Dus standaard alles dichtgevouwen, en pas open vouwen waneer iemand 'op het + knopje drukt'. Dan heb je nog steeds net zo veel queries als de recursieve functie, maar worden ze alleen uitgevoerd waneer de gebruiker er om vraagt.

Ken Thompson's famous line from V6 UNIX is equaly applicable to this post:
'You are not expected to understand this'


  • EfBe
  • Registratie: Januari 2000
  • Niet online
Ok, voor de search, ik post het complete artikel van Joe Celko (een van de Sql-92 standard board members) hier. Haal er je voordeel uit zou ik zeggen :)

Ik heb de handel wat geformat.
------------[(c) Joe Celko)]--------------------------------
The usual example of a tree structure in SQL books is called an
adjacency list model and it looks like this:

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 CREATE TABLE Personnel 
 (emp CHAR(10) NOT NULL PRIMARY KEY, 
  boss CHAR(10) DEFAULT NULL REFERENCES Personnel(emp), 
  salary DECIMAL(6,2) NOT NULL DEFAULT 100.00);


 Personnel 
 emp       boss      salary 
 ===========================
 'Albert'  'NULL'    1000.00
 'Bert'    'Albert'   900.00
 'Chuck'   'Albert'   900.00
 'Donna'   'Chuck'    800.00
 'Eddie'   'Chuck'    700.00
 'Fred'    'Chuck'    600.00


Another way of representing trees is to show them as nested sets.
Since SQL is a set oriented language, this is a better model than the
usual adjacency list approach you see in most text books. Let us
define a simple Personnel table like this, ignoring the left (lft) and
right (rgt) columns for now. This problem is always given with a
column for the employee and one for his boss in the textbooks. This
table without the lft and rgt columns is called the adjacency list
model, after the graph theory technique of the same name; the pairs of
nodes are adjacent to each other.

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 CREATE TABLE Personnel 
 (emp CHAR(10) NOT NULL PRIMARY KEY, 
  lft INTEGER NOT NULL UNIQUE CHECK (lft > 0), 
  rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
  CONSTRAINT order_okay CHECK (lft < rgt) );


 Personnel 
 emp         lft  rgt 
 ======================
 'Albert'      1   12 
 'Bert'        2    3 
 'Chuck'       4   11 
 'Donna'       5    6 
 'Eddie'       7    8 
 'Fred'        9   10


The organizational chart would look like this as a directed graph:

code:
1
2
3
4
5
6
7
8
9
            Albert (1,12)
            /        \
          /            \
    Bert (2,3)    Chuck (4,11)
                   /    |   \
                 /      |     \
               /        |       \
             /          |         \
        Donna (5,6)  Eddie (7,8)  Fred (9,10)


The first table is denormalized in several ways. We are modeling both
the personnel and the organizational chart in one table. But for the
sake of saving space, pretend that the names are job titles and that
we have another table which describes the personnel that hold those
positions.

Another problem with the adjacency list model is that the boss and
employee columns are the same kind of thing (i.e. names of personnel),
and therefore should be shown in only one column in a normalized
table. To prove that this is not normalized, assume that "Chuck"
changes his name to "Charles"; you have to change his name in both
columns and several places. The defining characteristic of a
normalized table is that you have one fact, one place, one time.

The final problem is that the adjacency list model does not model
subordination. Authority flows downhill in a hierarchy, but If I fire
Chuck, I disconnect all of his subordinates from Albert. There are
situations (i.e. water pipes) where this is true, but that is not the
expected situation in this case.

To show a tree as nested sets, replace the nodes with ovals, then nest
subordinate ovals inside each other. The root will be the largest
oval and will contain every other node. The leaf nodes will be the
innermost ovals with nothing else inside them and the nesting will
show the hierarchical relationship. The rgt and lft columns (I cannot
use the reserved words LEFT and RIGHT in SQL) are what shows the
nesting.

If that mental model does not work, then imagine a little worm
crawling anti-clockwise along the tree. Every time he gets to the
left or right side of a node, he numbers it. The worm stops when he
gets all the way around the tree and back to the top.

This is a natural way to model a parts explosion, since a final
assembly is made of physically nested assemblies that final break down
into separate parts.

At this point, the boss column is both redundant and denormalized, so
it can be dropped. Also, note that the tree structure can be kept in
one table and all the information about a node can be put in a second
table and they can be joined on employee number for queries.

To convert the graph into a nested sets model think of a little worm
crawling along the tree. The worm starts at the top, the root, makes
a complete trip around the tree. When he comes to a node, he puts a
number in the cell on the side that he is visiting and increments his
counter. Each node will get two numbers, one of the right side and
one for the left. Computer Science majors will recognize this as a
modified preorder tree traversal algorithm. Finally, drop the
unneeded Personnel.boss column which used to represent the edges of a
graph.

This has some predictable results that we can use for building
queries. The root is always (left = 1, right = 2 * (SELECT COUNT(*)
FROM TreeTable)); leaf nodes always have (left + 1 = right); subtrees
are defined by the BETWEEN predicate; etc. Here are two common
queries which can be used to build others:

1. An employee and all their Supervisors, no matter how deep the tree.

code:
1
2
3
4
 SELECT P2.*
   FROM Personnel AS P1, Personnel AS P2
  WHERE P1.lft BETWEEN P2.lft AND P2.rgt
    AND P1.emp = :myemployee;


2. The employee and all subordinates. There is a nice symmetry here.

code:
1
2
3
4
 SELECT P2.*
   FROM Personnel AS P1, Personnel AS P2
  WHERE P1.lft BETWEEN P2.lft AND P2.rgt
    AND P2.emp = :myemployee;


3. Add a GROUP BY and aggregate functions to these basic queries and
you have hierarchical reports. For example, the total salaries which
each employee controls:

code:
1
2
3
4
5
6
 SELECT P2.emp, SUM(S1.salary)
   FROM Personnel AS P1, Personnel AS P2,
        Salaries AS S1
  WHERE P1.lft BETWEEN P2.lft AND P2.rgt
    AND P1.emp = S1.emp 
  GROUP BY P2.emp;


4. To find the level of each node, so you can print the tree as an
indented listing.

code:
1
2
3
4
5
6
DECLARE Out_Tree CURSOR FOR
 SELECT P1.lft, COUNT(P2.emp) AS indentation, P1.emp 
   FROM Personnel AS P1, Personnel AS P2
  WHERE P1.lft BETWEEN P2.lft AND P2.rgt
  GROUP BY P1.emp
  ORDER BY P1.lft;


5. The nested set model has an implied ordering of siblings which the
adjacency list model does not. To insert a new node as the rightmost
sibling.

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
BEGIN
DECLARE right_most_sibling INTEGER;

SET right_most_sibling 
    = (SELECT rgt 
         FROM Personnel 
        WHERE emp = :your_boss);

UPDATE Personnel
   SET lft = CASE WHEN lft > right_most_sibling
                  THEN lft + 2
                  ELSE lft END,
       rgt = CASE WHEN rgt >= right_most_sibling
                  THEN rgt + 2
                  ELSE rgt END
 WHERE rgt >= right_most_sibling;

INSERT INTO Personnel (emp, lft, rgt)
VALUES ('New Guy', right_most_sibling, (right_most_sibling + 1))
END;


6. To convert an adjacency list model into a nested set model, use a
push down stack algorithm. Assume that we have these tables:

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-- Tree holds the adjacency model
CREATE TABLE Tree
(emp CHAR(10) NOT NULL,
 boss CHAR(10));

INSERT INTO Tree
SELECT emp, boss FROM Personnel;

-- Stack starts empty, will holds the nested set model 
CREATE TABLE Stack 
(stack_top INTEGER NOT NULL,
 emp CHAR(10) NOT NULL,
 lft INTEGER,
 rgt INTEGER);

BEGIN ATOMIC 
DECLARE counter INTEGER;
DECLARE max_counter INTEGER;
DECLARE current_top INTEGER;

SET counter = 2;
SET max_counter = 2 * (SELECT COUNT(*) FROM Tree);
SET current_top = 1;

INSERT INTO Stack 
SELECT 1, emp, 1, NULL
  FROM Tree
 WHERE boss IS NULL;

DELETE FROM Tree
 WHERE boss IS NULL;

WHILE counter <= (max_counter - 2)
LOOP IF EXISTS (SELECT * 
                   FROM Stack AS S1, Tree AS T1
                  WHERE S1.emp = T1.boss
                    AND S1.stack_top = current_top)
     THEN 
     BEGIN -- push when top has subordinates and set lft value
       INSERT INTO Stack
       SELECT (current_top + 1), MIN(T1.emp), counter, NULL
         FROM Stack AS S1, Tree AS T1
        WHERE S1.emp = T1.boss
          AND S1.stack_top = current_top;

        DELETE FROM Tree
         WHERE emp = (SELECT emp
                        FROM Stack
                       WHERE stack_top = current_top + 1);

        SET counter = counter + 1;
        SET current_top = current_top + 1;
     END
     ELSE 
     BEGIN  -- pop the stack and set rgt value
       UPDATE Stack
          SET rgt = counter,
              stack_top = -stack_top -- pops the stack
        WHERE stack_top = current_top
       SET counter = counter + 1;
       SET current_top = current_top - 1;
     END IF;
 END LOOP;
END;


This approach will be two to three orders of magnitude faster than the
adjacency list model for subtree and aggregate operations.

For details, see the chapter in my book JOE CELKO'S SQL FOR SMARTIES
(Morgan-Kaufmann, 1999, second edition)
Je kunt ook een pre-calc tabel gebruiken waarin je voor elke node in de tree alle parents in een rechte lijn naar de root opslaat. Die update je dan wanneer je een node toevoegt/verwijdert. Je kunt dan met een simpele select en een join snel de nodes ophalen.

edit:
volgens mij kloppen die CODE templates niet helemaal in react 1.9

[ Voor 5% gewijzigd door EfBe op 22-10-2003 17:50 ]

Creator of: LLBLGen Pro | Camera mods for games
Photography portfolio: https://fransbouma.com


Verwijderd

Topicstarter
@EfBe: das zeker een interessant artikel! Maar zoals het erop lijkt (heb het ff snel door gelezen) is dit niet direct toepasbaar op de huidige situatie binnen ons systeem.

Gelukkig heb ik wel een oplossing weten te vinden om binnen een recursieve functie niet steeds een query te doen om children te vinden. Met onderstaande query haal ik in één keer de tree structuur plat op met dit als resultaat: Zo kan ik met één query alles binnen halen en met ASP/VB de structuur netjes ordenen...

Commentaar blijft natuurlijk welkom :)

code:
1
2
3
4
5
6
7
8
9
10
  1  <top>   76
  1  <top>   30
  1  <top>   31
  1  <top>  104
 30 <andere titel1>   35
 30 <andere titel1>  435
 76 <andere titel2>   23
 76 <andere titel2>   24
 76 <andere titel2>   25
104 <andere titel3>  542



SQL:
1
2
3
4
5
6
7
8
9
10
11
12
SELECT  
    nm.ID,
    nm.Titel,

    nr.ChildID

FROM    navMenus nm

-- full join bepalen voor childID
FULL JOIN NavRelaties nr ON nm.ID = nr.ParentID

ORDER BY nm.ID ASC, nr.volgnr ASC
Pagina: 1