1. 程式人生 > >Mysql遞迴及行轉列,並優化

Mysql遞迴及行轉列,並優化

建立遞迴函式,根據專案rootId 找到其所有子專案 最終返回 以“,”連線在一起的子專案id串

    DROP FUNCTION IF EXISTS `queryChilProject`;

  CREATE DEFINER = `root`@`%` FUNCTION `queryChilProject`(rootId INT)
  RETURNS varchar(4000)
    BEGIN

     DECLARE sTemp VARCHAR(4000);


DECLARE sTempChd VARCHAR(4000);
SET sTempChd = cast(rootId as char);

WHILE sTempChd is not NULL DO

SET sTemp =(CASE when sTemp is null
                    then sTempChd
                else concat(sTemp,',',sTempChd)
                END);

SELECT group_concat(id) INTO sTempChd FROM projects where FIND_IN_SET(parent_id,sTempChd)>0;

END WHILE;

return sTemp;

END;

圖片







行轉列
select a.id,substring_index(substring_index(queryChilProject(a.id),',',b.help_topic_id+1),',',-1)
from
projects a
join
mysql.help_topic b
on b.help_topic_id < (length(queryChilProject(a.id)) - length(replace(queryChilProject(a.id),',',''))+1)
order by a.id;
這樣做雖然能達到效果,但是效率低。
最好是建立一箇中間表來提升查詢效率。

CREATE TABLE temp_project as select a.id,queryChilProject(a.id) as projects_ids from projects;
再將這張中間表進行行轉列
圖片

select a.id,substring_index(substring_index(a.projects_ids,',',b.help_topic_id+1),',',-1)
from
temp_project a
join
mysql.help_topic b
on b.help_topic_id < (length(a.projects_ids) - length(replace(a.projects_ids,',',''))+1)
order by a.id;
圖片
行轉列: http://www.cnblogs.com/cenalulu/archive/2012/08/20/2647463.html