Group mysql results by category and display them into groups under each category

后端 未结 4 790
别跟我提以往
别跟我提以往 2020-12-07 02:27

I am trying to create a simple css menu that gets the data from a mysql table.

My idea is to have menu like this

    Category 1
    - link 1
    - li         


        
相关标签:
4条回答
  • 2020-12-07 02:54

    I would use ORDER BY category instead. You can then iterate the result set like

    $old = null;
    foreach ($st as $s) {
      if $old != $s['id']
        echo 'Main category';
        $old = $s['id'];
      echo 'subcategory'
    

    Update

    There exist three possible solutions until now in this thread to the problem itself.

    Original option 1

    SELECT * FROM content group by category
    foreach
      SELECT * FROM content WHERE category=$cat['category']
    

    If one does only want to get each parent category once, one should use DISTINCT instead. One should not use GROUP BY without using any aggregation function. Combining GROUP BY with SELECT * is limited to (mostly) MySQL. You cannot select arbitrary columns in this case in ASNI SQL.

    A variant of option 1

    SELECT DISTINCT category FROM content ORDER BY category
    foreach
      SELECT * FROM content WHERE category=$cat['category']
    

    This is the corrected version with DISTINCT instead of GROUP BY.

    It still lacks of nested query calls. For 5 parent categories, this leads to 5 queries in the loop. For 10 parent categories, there are already 10 queries inside. One should avoid this kind of growing in general.

    Option 3

    SELECT * FROM content ORDER BY category, menu_name
    

    usable with the code above.

    This is preferable to the other options shown due to different reasons:

    • You only need one single database query to gather all data at once. The database spends (on easy queries) most of its time parsing the SQL statement one provided and only a fraction of time to actually gather the data you requested. If you provide lots of SQL code, it has to spend a lot of time parsing it. If you provide less code, it has less to do.
    • It is easier for a database to get the data once, sort it once and return it to you once, instead of gather a part, sort a part, return a part and start all over again.

    still unstated option 4

    There exists an until now unstated further solution. One can use prepared statements, prepare the SQL once and run it with different ids. This would still query all categories inside the loop, but would avoid the necessity to parse SQL code every time.

    Actually I do not know if this is better or worse (or sth. in between) than my solution.

    0 讨论(0)
  • 2020-12-07 02:57

    Your query is wrong

    $sql = "SELECT * FROM content WHERE group by category";
    

    should be

    $sql = "SELECT * FROM content group by category";
    

    Also since mysql is deprecated avoid using it. Use mysqli or PDO instead

    0 讨论(0)
  • 2020-12-07 03:08

    SQL GROUP BY statement groups the results so that only one row is returned for each category. This is typically used in conjunction with an aggregate function like count(), to count how many items are in each category. What you need is an either ORDER BY as GhostGambler said, or a separate query for each category as shown bellow. However as you only seem to have 2 categories, this approach seems unnecessarily complicated.

     $q=$db->query("SELECT DISTINCT category FROM content ORDER BY category");
     foreach($q as $cat){
        echo '<li id="'.$cat['category'].'" class="files">';  
        echo '<a href="'.$cat['category'].'">'.$cat['category'].'</a>'; 
        echo '<ul class="sub-menu">';
        $linkq=$db->query("SELECT * FROM content WHERE category='" . $cat['category'] . "'"); 
        foreach($linkq as $link){
           echo '<li><a href="#">'.$link['menu_name'].'</a></li>';
        }
        echo '</ul></li>';
     }
    
    0 讨论(0)
  • 2020-12-07 03:08

    I am assuming that you are wondering to add sub-menu dynamically. If so then first create a 2nd table for sub-menu and add relationship between menu and sub-menu tables.

    $select=$connection->query("select * from menus");
        while($result=$select->fetch_assoc()){
        echo "<li>";        
        echo "<a href=\"#\">".$result['MenuTitle']."</a>";
        $menuid=$result['MenuId'];
        if($result==true){
        $selectsubmenu=$connection->query("Select * from submenu where menuid='$menuid'");
            echo "<ul>";
                while($resultsubmenu=$selectsubmenu->fetch_assoc()){     
                        echo "<li><a href=\"Services.php?submenu=".$resultsubmenu['SubMenuId']."\">".$resultsubmenu['SubMenuTitle']."
                        </a></li>";
                        }
            echo "</ul>";
                    }
                echo "</li>";   
    }
    
    0 讨论(0)
提交回复
热议问题