我正在尝试从类别表中获取顶级父ID:
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
+-------------+----------------------+--------+
可能有很多子类别,我的问题是如何获得子类别的最高父级?
例如,在数据库子类别中,节点可以如下所示:
父>>子类别>> subsubcategory>> subsubsubcategory
另一个节点可能如下所示:
父>>子类别
因此,如果我查询id = 6的子类别的顶级父级,我会得到电子等等 如何用mysql获取顶级父ID?我希望,这完全可以理解。
答案 0 :(得分:2)
您必须编写一个循环查询的存储函数:
查询以查找父级
SELECT parent FROM cat WHERE category_id = 6
存储功能以查找顶级父级
DELIMITER $$
CREATE FUNCTION top_parent(PCat INTEGER) RETURNS INTEGER
BEGIN
DECLARE MyParent INTEGER;
DECLARE PrevParent INTEGER;
SET PrevParent = PCat;
REPEAT
SELECT parent INTO MyParent FROM cat WHERE category_id = PrevParent;
IF NOT(MyParent IS NULL) THEN
SET PrevParent = MyParent;
END IF;
UNTIL (MyParent IS NULL)
END REPEAT;
RETURN PrevParent;
END $$
DELIMITER ;
如何在查询中使用该功能
SELECT name FROM cat WHERE category_id = top_parent(6)
答案 1 :(得分:1)
@r := 7
无论你在这里给出的category_id将获得它的所有父级和提供限制1将获得顶级父级
SELECT T2.* FROM ( SELECT @r AS _category_id, (SELECT @r := parent FROM categories WHERE category_id = _category_id) AS parent, @l := @l + 1 AS lvl FROM (SELECT @r := 7, @l := 0) vars, categories WHERE @r <> 0) T1 JOIN categories T2 ON T1._category_id = T2.category_id ORDER BY T1.lvl DESC LIMIT 1;