A
A
Alexey2016-01-29 18:18:32
MySQL
Alexey, 2016-01-29 18:18:32

How to pull all parent records in the database?

Hello! I have such a table in the database:
5d363ec368e04c68bedb29ab18d7301a.jpg
For example, I refer to the category with id = 7 (Venus). To get the parent category for this category, I need to execute the query SELECT * FROM `category` WHERE `id` = 6
But how to pull out all the parent categories (I don’t know how many), namely to get a chain (venus -> planets -> space -> science)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DieZz, 2016-01-29
@DieZz

As far as I know, recursive queries cannot be used in mysql. Use nested sets , or multiple queries in a loop using the language you're writing in.

I
ivankomolin, 2018-02-27
@ivankomolin

An example of a recursive function that can be used to get a tree from a flat array.

/**
   * Формирует дерево
   * @param arr $items
   * @param int $parentId
   * @return arr
   */
  public function tree($items, $parentId = 0) {
    $tree = array();
    foreach($items as $item) {
      if ($item['parentId'] == $parentId) {
        $tree[$item['id']] = $item;
        $tree[$item['id']]['sub'] = $this->tree($items, $item['id']);
      }
    }

    return $tree;
  }

It is better of course to use some algorithm for storing trees in the database. There are many of them, one of them is nested sets, as recommended above. But the choice of algorithm should proceed from the conditions of a particular problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question