我研究了http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/并找到了解决您问题的方法。我想你已经有了你的解决方案,但是对于任何其他正在寻找相同解决方案的人,我在这里回答。
我的解决方案也适用于关系表,因为我们不能在关系表的父字段中设置零 (0)。它将为 NULL,我的解决方案也适用于关系表。
功能
DROP FUNCTION IF EXISTS hierarchy_connect_by_parent_eq_prior_id;
DELIMITER $$
CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INTEGER
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE _parent INT;
DECLARE _rank INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;
SET _parent = @id;
SET _rank = 0;
IF @id IS NULL THEN
RETURN NULL;
END IF;
LOOP
SET @innerrank = 0;
SELECT p.id
INTO @id
FROM (
SELECT id, @innerrank := @innerrank+1 AS rank
FROM yourTable
WHERE COALESCE(parent, 0) = _parent
ORDER BY yourField
) p
WHERE p.rank > _rank LIMIT 0, 1;
IF @id IS NOT NULL OR _parent = @start_with THEN
SET @level = @level + 1;
RETURN @id;
END IF;
SET @level := @level - 1;
SET @innerrank = 0;
SELECT COALESCE(p.parent, 0), p.rank
INTO _parent, _rank
FROM (
SELECT id, parent, @innerrank := @innerrank+1 AS rank
FROM yourTable
WHERE COALESCE(parent, 0) = (
SELECT COALESCE(parent, 0) FROM yourTable WHERE id = _parent
)
ORDER BY yourField
) p
WHERE p.id = _parent;
END LOOP;
END;
$$
DELIMITER ;
请替换yourTable
为您的表格名称和yourField
您想要对数据进行排序的字段名称。
查询
SELECT ou.* FROM (
SELECT hi.id, parent, yourField FROM (
SELECT hierarchy_connect_by_parent_eq_prior_id(id) AS id,
@level AS level
FROM (
SELECT @start_with := 0, @id := @start_with, @level := 0
) vars, yourTable
WHERE @id IS NOT NULL
) ho
JOIN yourTable hi ON hi.id = ho.id
) ou
请替换yourTable
为您的表格名称和yourField
您要显示的字段名称。
这将产生您需要的结果。我对其进行了测试并且效果很好。
这是http://sqlfiddle.com/#!9/9d060d/2以查看它的实际效果。