首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从一个按“父id”排序的表中选择数据

从一个按“父id”排序的表中选择数据
EN

Stack Overflow用户
提问于 2011-04-06 13:13:17
回答 4查看 2.5K关注 0票数 1

你能帮我写SQL select吗?

我有桌子:

各地区

(varchar(50))

  • parent_id (Int)
  • id (int)
  • name (int)

其中"parent_id“引用"id”。parent_id设置为0的行没有父行,并且位于顶部。我需要选择数据作为树。

我使用递归函数:)

代码语言:javascript
复制
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.'  ');
 }
}

我发现使用CTE ( Can I select full hierarchy of parents when id and parent id are in the same table? )是可能的,但也发现MySQL不支持CTE。

那么,在MySQL中是否有使用一个选择而不是递归函数的方法呢?谢谢:)

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-04-06 14:00:05

您可以使用非递归mysql存储过程,您可以按如下方式从php调用该存储过程:

示例调用

代码语言:javascript
复制
$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)

完整脚本和下面的测试数据

代码语言:javascript
复制
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);

希望这会有所帮助:)

票数 1
EN

Stack Overflow用户

发布于 2011-04-06 13:21:01

步骤1->

代码语言:javascript
复制
select distinct ID from tbl where PARENT_ID=0

将值存储在数组中,然后为每个值存储

步骤2->

代码语言:javascript
复制
select ID from TBL where PARENT_ID = $values_from_array

或者这会有用的

代码语言:javascript
复制
select ID from TBL where PARENT_ID in (select distinct ID from tbl where PARENT_ID=0) order by PARENT_ID
票数 0
EN

Stack Overflow用户

发布于 2011-04-06 13:27:43

来自我的MyBB插件的代码的一部分。它从等级论坛创建一个组合框->子>子。

代码语言:javascript
复制
function generate_video_category_select($name, $selectedId, $parent_id = 0, $depth = 1)
        {   
            global $db;
            $box = '';
            if($depth == 1)
            {
                $box .= '<select name="' . $name . '">';
                $box .='<option value="0" selected="selected">Boş</option>';
            }


            $sql = "SELECT * FROM ".TABLE_PREFIX."aofvideo_categories WHERE parent_id = ".$parent_id." ORDER BY name ASC";  

            $result = $db->query($sql);
            while($row = $db->fetch_array($result))
            {   
                $box .='<option value="'.$row['id'].'"'.($selectedId == $row['id'] ? ' selected="selected"' : '').'>'.str_repeat('&nbsp;',$depth).$row['name'].'</option>';
                $box .= generate_video_category_select($name,$selectedId,$row['id'],$depth + 5);
            }

            if($depth == 1)
                $box .="</select>";


            return $box;
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5566924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档