我有一个这样的表:
- id <
- 名称/gh>
- parent_id
然后我想根据它们的id选择某些行,所以像这样:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
我想,从这个查询,也显示父/子关系,如:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
所以最终输出看起来像这样:
1
--5
8
--9
----35
我是否在mysql之外这样做,我尝试过使用数组,但无法弄清楚,或
我是否在MYSQL中这样做,我也不知道怎么做。
这是我能想到的,似乎工作得很好。
ps -不好意思,格式不太清楚:( (fixed?)
- 我从MYSQL中获取parent_id和id并将其放入数组中数组键是id,值是父元素,在MYSQL的while循环中,像这样:
$testarray[$id] = $parent_id;
然后我通过下面的函数运行它,它按照我需要的方式排序。
function retrieveSubTree($parent, $myarray) { $tempArray = $myarray; $array = array(); //now we have our top level parent, lets put its children into an array, yea! while ($child = array_search($parent, $tempArray)) { unset($tempArray[$child]); //now lets get all this guys children if (in_array($child, $tempArray)) { $array[$child] = retrieveSubTree($child, $tempArray); } else { $array[$child] = true; } }//end while return (!empty($array)) ? $array : false; } function retrieveTree($myarray) { $array = array(); $counter = 0; foreach ($myarray as $key => $value) { $child = $key; $parent = $value; //if this child is a parent of somebody else if (in_array($child, $myarray) && $parent != '0') { while ($myarray[$parent] != '' && $myarray[$parent] != '0') { $newparent = $myarray[$parent]; $parent = $newparent; } if (!array_key_exists($parent, $array)) { $array[$parent] = retrieveSubTree($parent, $myarray); } } else { //now make sure they don't appear as some child if (!array_key_exists($parent, $myarray)) { //see if it is a parent of anybody if (in_array($child, $myarray)) { $array[$child] = retrieveSubTree($child, $myarray); } else { $array[$child] = true; } }//end if array key }//end initial in array }//end foreach return (!empty($array) ? $array : false); } $test = array( '1'=>'15', '2'=>'1', '3'=>'1', '4'=>'0', '5'=>'0', '6'=>'4', '7'=>'6', '8'=>'7', '9'=>'2', '10'=>'9' ); print_r(retrieveTree($test));
如果不改变表结构,则需要递归,而MySQL不支持递归。你得去别的地方做。您可以在PHP中编写递归函数,例如,使用宽度优先搜索来构建数组。在这里,看起来您正在使用parent_id
(0)来表示顶级对象。你可以搜索你的结果,并向你的数组中添加父元素为0的所有对象,这将给你一个包含1和8的数组。然后你可以递归:找到父元素为1的所有结果,并将其作为子数组添加到1;然后找到父元素为8的所有结果,并将它们添加为8的子数组。在每一关继续这样做,直到你的结果用完。
正如其他海报指出的,如果你可以改变表结构,你可以在MySQL中本地做到这一点。
相关文章:
- 在mysql.php上搜索
- MySQL/PHP将条件运算符(<;=,>;=)与WHERE子句中的字符串连接
- MySQL/PHP MySQL_fetch_array()一直缺少第一行
- MySQL PHP DELETE 在此实例上不起作用
- mysql/php:在字符串中查找起始字符串
- MySQL-PHP-避免多个查询来计算结果
- 如何编写嵌套查询MySQL PHP
- 更新数据库mysql.php中的序列号
- HTML-使用mysql.php生成一个选择框.我怎样才能更改“;值“;生成的选择框选项的
- MYSQL PHP脚本引发语法错误
- MySQL PHP查询问题
- 将表中的信息显示为已注册的用户ID或用户名MYSQL PHP
- mysql + php speed up
- 插入到使用相同的行(相同的主键)MySQL PHP PDO
- 统计与会者MYSQL/PHP
- PDO/MySQL/PHP-我的查询结果被缓存的问题
- MYSQL PHP:更新查询导致语法错误
- MYSQL PHP查询未插入数据
- MySQL/PHP:在一个查询中使用多个子查询来选择多个结果,这是一个坏主意吗?
- MySql.php中的换行符