【问题标题】:sql select all children AND grandchildren from a certain ancestor (root category)sql从某个祖先(根类别)中选择所有子孙
【发布时间】:2012-01-27 14:25:28
【问题描述】:

我有几个类别的图片。所有类别都在某个表中(比如说 tbl_categories)。子类别的级别介于 1 和 10 之间。 我想创建一个查询,提供来自某个根类别(可以是子类别本身)的所有子类别(及其子类别等)的 id。

例子:

 Category 1
    subcategory a
 Category 2
    subcategory b
        subsubcategory I
        subsubcategory II
    subcategory c

如果我使用类别 2,我想要子类别 b 和 c,结果是子类别 I en II。 听起来很简单,但我不知道。

我对编写查询还很陌生...

谢谢

【问题讨论】:

  • 你能展示一下你的实际表结构吗?
  • 还有您使用的是哪个 RDBMS(MySQL、PostgreSQL、Oracle 等)?
  • 我有一个 tbl_mm_cat,它有一个 uid_local(指 tbl_img 中图像的 id)和一个 uid_foreign(指 tbl_cat 中类别的 id)。嗯,我正在使用 CMS,它在后端有一个 phpMyAdmin 模块...我成功地使用它来检查哪些图像属于 2 类或 4 类: $sql = mysql_query ("SELECT uid_local FROM tbl_mm_cat WHERE uid_foreign IN( 2,4) AND uid_local ='".$item->getId()."'") or die(mysql_error()); getId() 只是获取每张图片的每一个 id(它是一个搜索模块,用户只能在某些类别中搜索)

标签: php mysql sql


【解决方案1】:

试试这个:

//Parents
$data = mysql_fetch_assoc(mysql_query("select id,name from categories where parent = 0"));

//Childrens
foreach( $data as $key => $row)
{
    $data[$key]['childrens'] = mysql_fetch_assoc(mysql_query("select id,name from categories where parent ='".mysql_real_escape_string( $row['id'] )."'"));

    //childrens
    foreach( $data[$key]['childrens'] as $_key => $_row )
    {
        $data[$key]['childrens'][$_key]['childrens'] = mysql_fetch_assoc(mysql_query("select id,name from categories where parent ='".mysql_real_escape_string( $_row['id'] )."'"));
    }
}

    //Print Array
print_r( $data );

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多