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

时间:2011-04-06 13:13:18

标签: php mysql

你能帮我写一下SQL select吗?

我得到了表:

REGIONS

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

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

知道我使用递归函数:)

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中使用一个select而不是递归函数? 谢谢:))

4 个答案:

答案 0 :(得分:0)

step1->

select distinct ID from tbl where PARENT_ID=0

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

步骤2->

select ID from TBL where PARENT_ID = $values_from_array

或者这可能会起作用

select ID from TBL where PARENT_ID in (select distinct ID from tbl where PARENT_ID=0) order by PARENT_ID

答案 1 :(得分:0)

MyBB插件的一部分代码。它从分层论坛创建了一个组合框 - > sub-> sub

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;
        }

答案 2 :(得分:0)

每当您需要从依赖于同一表中其他信息的表中提取信息时,最好使用两个引用相同表的“虚拟”表。在您知道关系只有两个深度的情况下,您可以使用以下内容:

从宗教a,宗教b中选择a.name,b.name,其中a.id = b.parent_id

3的示例如下:

从宗教a,宗教b,宗教c中选择a.name,b.name,c.name,其中a.id = b.parent_id

希望有所帮助。

答案 3 :(得分:0)

您可以使用非递归的mysql存储过程,您可以从您的php调用,如下所示:

示例调用

$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)

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

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);

希望这会有所帮助:)