douda5706 2011-04-06 13:13
浏览 93
已采纳

从“父ID”排序的一个表中选择数据

can you please help me write SQL select?

I got table:

REGIONS

  • id (int)
  • name (varchar(50))
  • parent_id (int)

where "parent_id" referees to "id". Rows with parent_id set to 0 has no parent and are on the top. I need to select data as tree.

Right know Im using recursive function :)

function SelectData($parent=0, $padding='')
{
 $q = mysql_query("SELECT * FROM regions WHERE parent=$parent");
 while($row = mysql_fetcharray($q))
 {
  echo($row[name]);
  priklad($row[id], $padding.'  ');
 }
}

I found out it is possible to do with CTE ( Can I select full hierarchy of parents when id and parent id are in the same table? ), but also found out that MySQL doesn't support CTE.

So, is there any way to use one select instead of recursive function in MySQL ? Thanks :)

  • 写回答

4条回答 默认 最新

  • duanke9540 2011-04-06 14:00
    关注

    You can use a non recursive mysql stored procedure which you can call from your php as follows:

    Example calls

    $result = $conn->query(sprintf("call category_hier(%d)", $catID));
    
    mysql> call category_hier(1);
    +--------+---------------+---------------+----------------------+-------+
    | cat_id | category_name | parent_cat_id | parent_category_name | depth |
    +--------+---------------+---------------+----------------------+-------+
    |      1 | Location      |          NULL | NULL                 |     0 |
    |      3 | USA           |             1 | Location             |     1 |
    |      5 | Chicago       |             3 | USA                  |     2 |
    |      4 | Illinois      |             3 | USA                  |     2 |
    +--------+---------------+---------------+----------------------+-------+
    4 rows in set (0.00 sec)
    
    mysql> call category_hier(2);
    +--------+---------------+---------------+----------------------+-------+
    | cat_id | category_name | parent_cat_id | parent_category_name | depth |
    +--------+---------------+---------------+----------------------+-------+
    |      2 | Color         |          NULL | NULL                 |     0 |
    |      6 | Black         |             2 | Color                |     1 |
    |      7 | Red           |             2 | Color                |     1 |
    +--------+---------------+---------------+----------------------+-------+
    3 rows in set (0.00 sec)
    

    Full script and test data below

    drop table if exists categories;
    create table categories
    (
    cat_id smallint unsigned not null auto_increment primary key,
    name varchar(255) not null,
    parent_cat_id smallint unsigned null,
    key (parent_cat_id)
    )
    engine = innodb;
    
    insert into categories (name, parent_cat_id) values
    ('Location',null), 
    ('Color',null), 
       ('USA',1), 
          ('Illinois',3), 
          ('Chicago',3), 
       ('Black',2), 
       ('Red',2);
    
    
    drop procedure if exists category_hier;
    delimiter #
    
    create procedure category_hier
    (
    in p_cat_id smallint unsigned
    )
    begin
    
    declare v_done tinyint unsigned default 0;
    declare v_depth smallint unsigned default 0;
    
    create temporary table hier(
     parent_cat_id smallint unsigned, 
     cat_id smallint unsigned, 
     depth smallint unsigned default 0
    )engine = memory;
    
    insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;
    create temporary table tmp engine=memory select * from hier;
    
    /* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */
    
    while not v_done do
    
        if exists( select 1 from categories c
            inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth) then
    
            insert into hier select c.parent_cat_id, c.cat_id, v_depth + 1 from categories c
                inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth;
    
            set v_depth = v_depth + 1;          
    
            truncate table tmp;
            insert into tmp select * from hier where depth = v_depth;
    
        else
            set v_done = 1;
        end if;
    
    end while;
    
    select 
     c.cat_id,
     c.name as category_name,
     p.cat_id as parent_cat_id,
     p.name as parent_category_name,
     hier.depth
    from 
     hier
    inner join categories c on hier.cat_id = c.cat_id
    left outer join categories p on hier.parent_cat_id = p.cat_id
    order by
     hier.depth;
    
    drop temporary table if exists hier;
    drop temporary table if exists tmp;
    
    end #
    
    delimiter ;
    
    call category_hier(1);
    
    call category_hier(2);
    

    Hope this helps :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)