【发布时间】:2018-04-25 15:23:42
【问题描述】:
我想创建一个 mysql 函数,该函数可以使用表 category 中的列 related 找到所有相关的祖先,然后使用所有这些祖先(子、孙...) id,包括它自己来查找listing_category 中的那些 ID 使用列 category。
类别
ID, Related
1,0
2,1
3,1
4,1
5,0
6,5
7,1
8,7
9,7
10,1
如果我选择 1,那么 2,3,4,7,10 是它的孩子,8,9 是它的孙子。
listing_category
Category
1
1
2
3
3
5
6
9
7
7
所以现在我想创建一个 MySql 函数,它可以在另一个名为 listing_category 的表中计算 1、2、3、4、7、10、8、9 的所有实例
create function listing_count(ID int(11)) returns int(11)
begin
declare count int(11);
set count=(select count(*) from listing_category where category=ID);
while (select id from category where related=ID) as childID and count<100 do
set count=count+listing_count(childID);
end while;
return count;
end
所以listing_count(1) 会在category 中找到所有亲戚 2,3,4,7,10,8,9,然后计算 1,2,3,4,7,10,8,9 里面的所有实例listing_category。因此在本例中将返回 8 个计数。
可以用mysql存储过程吗?
【问题讨论】:
-
尝试使用关系将表与自身连接起来并进行计数。如果需要父母 -> 孩子 -> 孙子,则需要加入两次表。
-
您的
9的返回值似乎不正确。不应该是8吗? -
@clinomaniac 是的,你是对的。 8就是答案
-
是否可以在“select in”语句中声明一个数组并使用该数组