mysql select with while循环

vddsk6oq  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(370)

我想从表中选择数据,并使用其中一列创建一个循环来定义其他数据。
例如:

'select id,related_id,name from ancestors'

id, related_id, name
1, 0, Bob
2, 1, Dave
3, 2, Susie
4, 1, Luke
5, 0, Cindy
6, 5, Sam

鲍勃是爷爷,戴夫和卢克是他的孩子,苏茜是他的孙女。辛迪有个孩子萨姆。
现在,我想用 related_id 来计算祖先树的等级。所以我希望结果是:

id, related_id, name, level
1, 0, Bob, 0
2, 1, Dave, 1
3, 2, Susie, 2
4, 1, Luke, 1
5, 0, Cindy, 0
6, 5, Sam, 1

我想创建如下查询:

select id,related_id,name from ancestors; 
while related_id<>0 do level=level+1; 
select related_id from ancestors where id=related_id end;

在树上循环并计算每个人在他/她的树中的级别。
这是我的实现。我好像没法使用“获取”级别。我得到一个错误,我不能在fetchall上使用boolean。有什么问题吗?

$connection->exec('
   DELIMITER $$
   DROP FUNCTION IF EXISTS `get_level` $$
   CREATE FUNCTION `get_level`(VAR int(11)) RETURNS int(11) 
   DETERMINISTIC
   BEGIN 
   DECLARE level int(11);
   DECLARE parent int(11);
   set level=0;
   set parent=(select related_id from category where id=VAR);
   while parent>0 DO
   set level=level+1;
   set parent=(select related_id from category where id=parent);
   END 
   WHILE; 
   return level;
   END$$
   DELIMITER;');

   $fetch=$connection->query('select *,get_level(id) as level from category')->fetchall(pdo::FETCH_UNIQUE|pdo::FETCH_ASSOC);
   print_r($fetch);
x759pob2

x759pob21#

您可以创建mysql函数来获取记录级别,然后在查询中调用它。函数输入将是记录id并输出级别号。函数将是这样的

DELIMITER $$
DROP FUNCTION IF EXISTS `getlevel` $$
CREATE FUNCTION `get_level`(Id int(11)) RETURNS int(11) 
    DETERMINISTIC
BEGIN 
DECLARE levelNumber int(11); -- declare variable to record level
DECLARE parent int(11); -- declare variable to hold the parent id
set levelNumber = 0; -- set the level to zero at the begining
set parent = (select `relation_column` from `table` where `id_column` = Id); -- get parent record of then id givin to function
while parent > 0 DO  -- loop unitl parent = 0 or record has no parent
set levelNumber = levelNumber + 1; -- increase level by 1
set parent = (select `relation_column` from `table` where `id_column` = parent); -- re set parent id
END 
WHILE; 
return levelNumber; -- return then level number
END$$
DELIMITER ;

relationship\列是保存记录关系的列。id\列是保存记录id或(主键)的列。
最终查询将如下所示

select `table`.`id_column`,`table`.`relation_column`,`table`.`name`,get_level(`table`.`id_column`) as  "level" from `table`

希望这会有帮助

相关问题