创建一个自定义函数:

set global log_bin_trust_function_creators=;
 DELIMITER $$

 USE `dressv_website`$$

 DROP FUNCTION IF EXISTS `fn_QueryRelation`$$

 CREATE DEFINER=`sa`@`%` FUNCTION `fn_QueryRelation`(AreaId INT,Relation TINYINT()) RETURNS VARCHAR() CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR();
DECLARE sTempChd VARCHAR();
SET sTemp = '$';
SET sTempChd = CAST(AreaId AS CHAR);
IF Relation= THEN
WHILE sTempChd IS NOT NULL DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT GROUP_CONCAT(parentId) INTO sTempChd FROM product_leimu WHERE FIND_IN_SET(id,sTempChd)>;
END WHILE;
ELSE
WHILE sTempChd IS NOT NULL DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT GROUP_CONCAT(id) INTO sTempChd FROM product_leimu WHERE FIND_IN_SET(parentId,sTempChd)>;
END WHILE;
END IF;
RETURN sTemp;
END$$ DELIMITER ;

fn_QueryRelation

查询语句:

 SELECT * FROM product_leimu WHERE FIND_IN_SET(id, fn_QueryRelation(,)); 

MYSQL

05-11 19:24