我希望它能帮助你。
表结构
CREATE TABLE IF NOT EXISTS `products_t` (
`id` int(11) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`parent_id` varchar(100) DEFAULT NULL,
`sub_id` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `products_t` (`id`, `name`, `parent_id`, `sub_id`) VALUES
(74, 'category15', '47', NULL),
(75, 'category16', '47', NULL),
(76, 'category19', NULL, '75'),
(77, 'category20', NULL, '76'),
(80, 'category80', NULL, '50'),
(81, 'category81', '50', NULL);
查询
select id,
name,
IFNULL(parent_id,'47' ) as parent_id
from (select * from products_t
order by parent_id, id) products_sorted,
(select @pv := '47') initialisation
where (find_in_set(parent_id, @pv) or find_in_set(sub_id, @pv) )
and length(@pv := concat(@pv, ',', id))
在这里,@pv:='47'中指定的值应该设置为要选择其所有子代的父代的id。
结果
id name parent_id
74 category15 47
75 category16 47
76 category19 47
77 category20 47