如何改善查询-PHP,MSSQL-两级水平菜单

时间:2018-06-19 18:20:03

标签: php sql-server

我有一个父级/子级水平菜单...第一个查询找到顶层项目,然后第二个查询使用该信息循环并查询每组子项目-此查询花费的时间太长。如何加快速度?

 <ul>
   <?php 
     //query top level navigation
     $tsqlnav = "SELECT DISTINCT id_division AS id, id_division_slot AS slot, parent FROM [xxx].[dbo].[service_div] WHERE id_service = ? AND content_languages_list LIKE ? AND (parent ='' or parent is NULL) ORDER BY slot;";
     $paramsnav = array($lang_id_service, '%'.$_SESSION['id_language'].'%');
     $optionsnav =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
     $stmtnav = sqlsrv_query($conn, $tsqlnav, $paramsnav, $optionsnav);
     if($stmtnav === false) {die( print_r( sqlsrv_errors(), true ));}
     $row_countnav = sqlsrv_num_rows( $stmtnav );
     if ($row_countnav === false) {echo "Error in retrieving row count."; }
     elseif ($row_countnav > 0) {
       $div='0';
       while( $row = sqlsrv_fetch_array( $stmtnav, SQLSRV_FETCH_ASSOC) ) {
         $parent = $row['parent'];
         $id_div = $row['id'];
         $id_div_slot = $row['slot'];
         echo "<li>".$row['id'];
            echo "<ul>";
             $tsqlnav2 = "SELECT DISTINCT id_module AS id, id_module_slot AS slot, parent FROM [xxx].[dbo].[service] WHERE id_service = ? AND content_languages_list LIKE ? AND id_division = ? ORDER BY slot;";
             $paramsnav2 = array($lang_id_service, '%'.$_SESSION['id_language'].'%', $id_div);
             $optionsnav2 =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
             $stmtnav2 = sqlsrv_query($conn, $tsqlnav2, $paramsnav2, $optionsnav2);
             if( $stmtnav2 === false ) { die( print_r( sqlsrv_errors(), true )); }
             $row_countnav2 = sqlsrv_num_rows( $stmtnav2 );
             if ($row_countnav2 === false) {echo "Error in retrieving row count."; }
             elseif ($row_countnav2 > 0) { 
               while( $row2 = sqlsrv_fetch_array( $stmtnav2, SQLSRV_FETCH_ASSOC) ) {
                 $id_mod = 'm'.$row2['id']; 
                 echo "<li>".$id_mod."</li>";
               }
             }
           echo "</ul>";
         echo "</li>";  
       }
     }
   ?>
 </ul>

1 个答案:

答案 0 :(得分:1)

我建议将此逻辑分为两个。

  1. 获取您的顶级商品并创建所有顶级商品的数组。
  2. 在顶级项目数组上运行循环并获取每个顶级的子项目 一一列出。

现在,在关闭初始请求之前,您正在发出多个数据库请求。一次应该有一个数据库调用。