在哪里放置限制条款?

时间:2012-09-24 21:10:18

标签: php limit limit-clause

我试图在数据库查询上放置一个限制条款,只显示前4个结果。

我正在使用的当前代码是

    $categories_query = "select c.categories_id, cd.categories_name, c.parent_id
                      from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd 
                       where c.categories_id = cd.categories_id
                       and c.categories_status=1 " .
//                             "and c.categories_id = ptc.category_id " .
//                             "and ptc.category_id = cd.categories_id " .
//                             "and ptc.product_type_id not in  " . $this->document_types_list . "
                       " and cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                         order by c.parent_id, c.sort_order, cd.categories_name";
         $categories = $db->Execute($categories_query);
         while (!$categories->EOF) {
           $this->data[$categories->fields['parent_id']][$categories->fields['categories_id']] = array('name' => $categories->fields['categories_name'], 'count' => 0);
           $categories->MoveNext();
         }

我遇到的问题是我找到了一种方法,通过在订单查询后放置LIMIT 4来限制仅4个结果,并且它显示前4个父类别,但它也从列表中删除子类别。

所以我想接受这个

<ul>
   <li>Menu One</li>
   <li>Menu Two
      <ul>
         <li>Submenu One</li>
         <li>Submenu Two</li>
         <li>Submenu Three</li>
      </ul>
   </li>
   <li>Menu Three</li>
   <li>Menu Four</li>
   <li>Menu Five</li>
   <li>ect...</li>
</ul>

并看到这个

<ul>
   <li>Menu One</li>
   <li>Menu Two
      <ul>
         <li>Submenu One</li>
         <li>Submenu Two</li>
         <li>Submenu Three</li>
      </ul>
   </li>
   <li>Menu Three</li>
   <li>Menu Four</li>
</ul>

当在查询中放置'LIMIT 4'时,它只显示此

<ul>
   <li>Menu One</li>
   <li>Menu Two</li>
   <li>Menu Three</li>
   <li>Menu Four</li>
</ul>

如何将子类别与父类别保持一致?通常只调用前4个不会调用它下面的类别

1 个答案:

答案 0 :(得分:0)

查询正在完全按照您的要求执行 - &#34; LIMIT&#34;意味着您只返回4条记录,按categoryID排序。

为了得到你想要的东西,你必须重新改写查询 - 我还没有在这台笔记本电脑上安装SQL,所以很难测试,但是这样的话:

$categories_query = "select c.categories_id, cd.categories_name, c.parent_id
                      from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd 
                       where c.categories_id = cd.categories_id
                       and c.categories_status=1 " .
                       " and cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                       " and c.parent_id in " .
                       " ( select parent_id from " . TABLE_CATEGORIES . " limit 4) " .
                       "  order by c.parent_id, c.sort_order, cd.categories_name";
         $categories = $db->Execute($categories_query);
         while (!$categories->EOF) {
           $this->data[$categories->fields['parent_id']][$categories->fields['categories_id']] = array('name' => $categories->fields['categories_name'], 'count' => 0);
           $categories->MoveNext();
         }