有个商品类别表如下结构:
create table Category
(
   id                   bigint not null auto_increment,  //商品id
   Cat_id               bigint,                          //商品父类id
   cnName               varchar(100),                    //中文名
   enName               varchar(100),                    //英文名
   LevelNum             int,                             //所在层次
   description          varchar(500),
   primary key (id)
);
现在我想随便输入一个类别id ,想查出其所有子类列表,需要统计出每个子类下的商品数量,我的问题是怎么统计子类下的商品数量,因为子类下边有可能有下一级子类,商品类别6层以上,类似于淘宝

解决方案 »

  1.   

    用一句SQL做不到,因为在向下递归检查是否为叶节点。 在你的程序中实现了。
      

  2.   

    没有sql高手愿意帮我解决这个问题么?
      

  3.   

    一般用递归解决,用SQL语句的话,若干LEFT JOIN
      

  4.   

    可以转化下思路, 把 category 的id 设为字符型的, 比如 varchar(255).假设每个类别下的 直接子类别不超过 999 个。category id一级类别。
    --------------
    001
    002
    003
    ...二级类别
    -------------
    001001
    001002
    001003 
    ...如果要统计 001 类别下的 商品数量的话, 可以在 product 表中
    select count(*) from product where category_id like concat('001', '%')
      

  5.   

    比起递归来说, 这个效率是很高的, 虽然浪费了点空间。 但是很简单,灵活。
    也很容易知道  LevelNum = length(category id) / 3
    比如 
    length('001')/3 = 1.
    length('001001') / 3 = 2 
      

  6.   

    先建一个临时表
    用递归把符合条件的类编号写到临时表里,然后select count ……where id in(select id from temptable)
      

  7.   

    变一下结构create table Category 

      id                  bigint not null auto_increment,  //商品id 
      Cat_code              varchar,                          //商品代号  1-2-3
      cnName              varchar(100),                    //中文名 
      enName              varchar(100),                    //英文名 
      LevelNum            int,                            //所在层次 
      description          varchar(500), 
      primary key (id) 
    ); 通过code,[-]的个数 来表示商品的层次