Select category and subcategory within the same table

Asked

Viewed 606 times

1

I have the table called modulos Inside it I include idModule, idModuloBase, module, folder and dating creation

When the idModuloBase is 0, it is the category, if it is > 0, it is the completed module. I need to make an SQL that lists the categories and subcategories within each one...

Este seria o baco de dados E esta é a lista que preciso ter

Can anyone suggest me any SQL to do that? Thank you.

  • You only have 2 levels of categories, or this is undetermined?

  • There are only two levels: 0 - main category - >0 is the category that is filled... To avoid making two separate tables of category and subcategory...

2 answers

3


As there are only two levels, just one JOIN of the table with itself (a self John):

SELECT
   modulo.*, 
   principal.idModulo AS idModuloBase,
   principal.modulo AS moduloBase,
   principal.pasta AS pastaBase
FROM modulos AS modulo
INNER JOIN modulos AS principal
ON principal.idModulo = modulo.idModuloBase

1

I don’t see a query that can solve the problem well, so I suggest doing it in PHP.

<?php

  $sql = "SELECT * FROM modulos WHERE idMoludoBase = 0";
  // Execute sua query

  $modulos = Array();
  while ($row = $res->fetch()) {

     $sql = "SELECT * FROM modulos WHERE idMoludoBase = {$row['idModulo']}";
     // Execute sua query

     // Se ten submodulos
     if ($sres){
        // Adicione todos na chave submodulos
        $row['submodulos'] = $sres->fetchAll();
     }

     // Adicona a linha ao array de modulos
     $modulos[] = $row;
  }

The code acime is "only an algorithm", must be adapted according to its drive of database.

Variable output $modulos:

  $modulos => Array(
     [
        idModulo      => 1
        idModuloBase  => 0 
        modulo        => Cadastros
        ...
        submodulos    => Array(
           [
              idModulo       => 2
              idModuloBase   => 1
              modulo         => Cedentes
              ...
           ],
           [ ... ]
        )
     ], 
     [ ... ]
  )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.