此函数当前获取比父类别低一级的子类别。我们知道父类别($category_id),它会检查子类别并正确返回结果。
// list category for the category (type)
function getCategoryItemsList($category_id) {
$cat_list = $category_id;
// check for child category
$sql = "select category_id from category where category_parent_id = $category_id ";
$cat_ids = getSqlResult($sql, SQL_RESULT_ALL);
foreach($cat_ids as $item) {
$cat_list = $cat_list . ',' . $item['category_id'];
}
return $cat_list;
}
问题是当我们有多个类别级别时,例如:
父母>子女>孙子>曾孙
如何返回父级的所有子类别级别?
///// MYSQL CATEGORY DB
category_id category_name category_parent_id
1 shoes 0
2 blue shoes 1
3 men blue shoes 2
4 men blue shoe small 3
5 red shoes 1
6 men red shoes 5
7 shirts 0
当 $category_id='1' 为 2,3,4,5,6 时,预期结果
试试这个:
create table category(
id int,
name varchar(100),
parent_id int
);
insert into category values
(1, 'shoes', 0),
(2, 'blue shoes', 1),
(3, 'men blue shoes', 2),
(4, 'men blue shoe small', 3),
(5, 'red shoes', 1),
(6, 'men red shoes', 5),
(7, 'shirts', 0);
SELECT GROUP_CONCAT(lv SEPARATOR ',') FROM (
SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM category WHERE
FIND_IN_SET(parent_id, @pv)) AS lv FROM category
JOIN (SELECT @pv:=1)tmp
WHERE parent_id IN (@pv)) a;
输出:
mysql> SELECT GROUP_CONCAT(lv SEPARATOR ',') FROM (
-> SELECT @pv:=(SELECT GROUP_CONCAT(id SEPARATOR ',') FROM category WHERE
-> FIND_IN_SET(parent_id, @pv)) AS lv FROM category
-> JOIN (SELECT @pv:=1)tmp
-> WHERE parent_id IN (@pv)) a;
+--------------------------------+
| GROUP_CONCAT(lv SEPARATOR ',') |
+--------------------------------+
| 2,5,3,6,4 |
+--------------------------------+
1 row in set (0.00 sec)
SQLFiddle demo
此解决方案基于该答案
任意高度的树状父/子结构的表中的所有父项或子项,我所知道的最好(也许是唯一)方法是使用递归查询。一开始可能有点难以掌握,但一旦你让它发挥作用,它就会成为很好的锻炼和迷人的东西。这里有解释和示例:https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx
编辑:你所问的问题可能在概念上存在问题。我假设一个类别可以有多个子项,查询无法"知道"要选择哪个子项,因此将选择所有子项。在您的示例中,只有一个子 pr. 类别,在这种情况下,查询有效,但您应该牢记此假设。但是,在下面的查询中,只需在每个类别中选择父级就相当容易了。这是我的建议:
BEGIN
WITH ct
AS (
SELECT c1.Id,
0 Step,
c1.ParentCategoryId
FROM _Category c1
WHERE c1.Id = 132
UNION ALL
SELECT c2.Id,
ct.Step + 1,
c2.ParentCategoryId
FROM _Category c2
JOIN ct
ON c2.ParentCategoryId = ct.Id
)
SELECT ct.Id,
ct.Step
FROM ct;
END