How do you convert a parent-child (adjacency) table to a nested set using PHP and MySQL?

后端 未结 2 1759
我在风中等你
我在风中等你 2020-12-07 19:25

I\'ve spent the last few hours trying to find the solution to this question online. I\'ve found plenty of examples on how to convert from nested set to adjacency... but few

2条回答
  •  一向
    一向 (楼主)
    2020-12-07 19:46

    Bash converting:

    # SQL command to fetch necessary fields, output it to text archive "tree"
    SELECT id, parent_id, name FROM projects;
    
    # Make a list "id|parentid|name" and sort by name
    cat tree |
      cut -d "|" -f 2-4 |
      sed 's/^ *//;s/ *| */|/g' |
      sort -t "|" -k 3,3 > list
    
    # Creates the parenthood chain on second field
    while IFS="|" read i p o
    do
      l=$p
      while [[ "$p" != "NULL" ]]
      do
        p=$(grep -w "^$p" list | cut -d "|" -f 2)
        l="$l,$p"
      done
      echo "$i|$l|$o"
    done < list > listpar
    
    # Creates left and right on 4th and 5th fields for interaction 0
    let left=0
    while IFS="|" read i l o
    do
      let dif=$(grep "\b$i,NULL|" listpar | wc -l)*2+1
      let right=++left+dif
      echo "$i|$l|$o|$left|$right"
      let left=right
    done <<< "$(grep "|NULL|" listpar)" > i0
    
    # The same for following interactions
    n=0
    while [ -s i$n ]
    do
      while IFS="|" read i l nil left nil
      do
        grep "|$i,$l|" listpar |
        while IFS="|" read i l o
        do
          let dif=$(grep "\b$i,$l|" listpar | wc -l)*2+1
          let right=++left+dif
          echo "$i|$l|$o|$left|$right"
          let left=right
        done
      done < i$n > i$((++n))
    done
    
    # Show concatenated
    cat i*|sort -t"|" -k 4n
    
    # SQL commands
    while IFS="|" read id nil nil left right
    do
      echo "UPDATE projects SET lft=$left, rgt=$right WHERE id=$id;"
    done <<< "$(cat i*)"
    

提交回复
热议问题