求助:
有一商品分类表tgoodstype ,做递归分类,表结构数据如下
如果直接写sql
SELECT ParentID FROM tgoodstype where GoodsTypeID= 44 -- 或 = '44'
不用想,结果肯定是 40
想写个函数 传入一个分类的id,得到该分类的所有父类的Id 以‘,’分开
第一次用函数 ,写网上查了下资料 ,写了下面这个样的sql
drop Function IF EXISTS fGetGoodsTypeParentIdList;
DELIMITER $$
CREATE FUNCTION `dbshop`.`fGetGoodsTypeParentIdList` (goodsTypeId int)
RETURNS text
BEGIN
declare tempList text;
declare tempChilidId varchar(1000);
SET tempList='';
SET tempChilidId = cast(goodsTypeId as CHAR);
-- 此处应该为while循环 set temp那一句应该在select前面
-- 这里去掉是为了测试验证 第一次的查询就会出现问题
SELECT ParentID into tempChilidId FROM tgoodstype
where GoodsTypeID= tempChilidId limit 1;
SET tempList= CONCAT(tempList,',',tempChilidId);
RETURN tempList;
END
函数创建完成后,调用
select fGetGoodsTypeParentIdList(44);
得到的结果出乎我的意外 为 : ,-2
如果不在where后面加上 limit 1
直接会报错,提示的意思应该是 查询的结果为多条数据 不能执行into
而这个-2正是那个表的数据中的第一条数据的ParentID的值
所以可以肯定的是 select后面的 where 没有起作用
我试过另外定义个变量在where后面那里去比较 而不是直接跟into那个变量比较
结果还是一样
弄了半天时间了,还是没找到怎么解决,求大神指点!