在sql中的嵌套表中返回父ID

时间:2014-02-26 06:06:19

标签: mysql sql

这是mysql中的一个表。

子表:

id    name    parent_id
1     sub       0     //it means this the sub has not any parents.
2     sub1      1     //it means the parent is sub
3     sub2      1
4     sub3      3
5     sub4      4
6     sub5      0
7     sub6      6

如何提供ID号并获取其根父ID?

例如:

如果ID = 5,则返回1

如果ID = 6,则返回6

如果ID = 7,则返回6

SELECT id from table sub_table
WHILE parent_id != 0
BEGIN
    ...?..
END

3 个答案:

答案 0 :(得分:1)

使用PHP,您可以通过以下方式实现此目的:

    $id = 5;$parent_id = 5; /* set default to values you want*/

    while($parent_id != 0)
    {

       $sql = 'SELECT id,parent_id from sub_table where id = $parent_id ';
       $rs= $mysqli->query($sql);  /* fetch details */
       $old_id = $id; /* this will save the last id in current iteration */
       $parent_id = $rs['parent_id'];
       $id = $rs['id'];

    }

因此,一旦退出循环,您的结果将保存在$old_id

答案 1 :(得分:1)

您可以使用以下功能:

DELIMITER $$ 
CREATE FUNCTION dnmtr_topid(input_id INT UNSIGNED) 
RETURNS INT UNSIGNED 
BEGIN 
DECLARE in_id INT UNSIGNED; 
DECLARE v_pid INT UNSIGNED; 
SET in_id := input_id; 
WHILE in_id > 0 DO 
SET v_pid := in_id; 
SELECT parent_id into in_id FROM dnmtr_all_category WHERE id = in_id LIMIT 1; 
END WHILE; 
RETURN v_pid; 
END $$

然后您可以使用SELECT HATEST(x)来获得结果。

答案 2 :(得分:1)

DROP FUNCTION IF EXISTS HATEST;
DELIMITER //
CREATE FUNCTION HATEST(input_id INT UNSIGNED)
  RETURNS INT UNSIGNED
BEGIN
  DECLARE in_id   INT UNSIGNED;
  DECLARE v_pid  INT UNSIGNED;

  SET in_id := input_id;

  WHILE in_id > 0 DO
    SET v_pid := in_id;
    SELECT parent_id into in_id FROM TABLE1 WHERE id = in_id LIMIT 1;
  END WHILE;

  RETURN v_pid;
END//
DELIMITER ;