mysql樹形結構查詢(預存程序)

來源:互聯網
上載者:User

就用資料資料庫表地址資料(中國地區)來說吧(用Windows請使用gbk !!)

可直接運行(去除註解)

預存程序:

DELIMITER //
drop procedure if exists findLChild//
/* iid 遞迴父節點 , layer 允許遞迴深度 */
CREATE PROCEDURE findLChild(iid bigint(20),layer bigint(20))
BEGIN
/*建立接受查詢的暫存資料表 */
create temporary table if not exists tmp_table(id bigint(20),name varchar(50)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*最高允許遞迴數*/
SET @@max_sp_recursion_depth = 99 ;
call iterative(iid,layer);/*核心資料收集*/
select * from tmp_table ;/* 展現 */
drop temporary table if exists tmp_table ;/*刪除暫存資料表*/
END;//
DELIMITER ;
DELIMITER //
drop procedure if exists iterative //
CREATE PROCEDURE iterative(iid bigint(20),layer bigint(20))
BEGIN
declare tid bigint(20) default -1 ;
declare tname varchar(50) character set utf8;
/* 遊標定義 */
declare cur1 CURSOR FOR select id,name from location where fid=iid ;
declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tid = null;
/* 允許遞迴深度 */
if layer>0 then
OPEN cur1 ;
FETCH cur1 INTO tid,tname ;
WHILE ( tid is not null )
DO
/* 核心資料收集 */
insert into tmp_table values(tid,tname);
call iterative(tid,layer-1);
FETCH cur1 INTO tid,tname ;
END WHILE;
end if;
END;//
DELIMITER ;

//運行!!

mysql> call findLChild(1,1);
+------+------------------+
| id  | name       |
+------+------------------+
|  2 | 北京       |
|  4 | 上海       |
|  6 | 香港特別行政區  |
|  8 | 澳門特別行政區  |
|  10 | 河北       |
|  23 | 山西       |
|  35 | 遼寧       |
|  50 | 吉林       |
|  60 | 黑龍江      |
|  74 | 江蘇       |
|  88 | 浙江       |
| 101 | 安徽       |
| 119 | 福建       |
| 129 | 江西       |
| 142 | 山東       |
| 160 | 河南       |
| 179 | 湖北       |
| 198 | 湖南       |
| 213 | 廣東       |
| 235 | 甘肅       |
| 250 | 四川       |
| 272 | 貴州       |
| 282 | 海南       |
| 301 | 雲南       |
| 318 | 青海       |
| 327 | 陝西       |
| 348 | 廣西壯族自治區  |
| 363 | 西藏自治區    |
| 371 | 寧夏回族自治區  |
| 377 | 新疆維吾爾自治區 |
| 400 | 內蒙古自治區   |
| 413 | 台灣省      |
+------+------------------+
32 rows in set (0.02 sec)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.