mysql版本(5.5、6等等)尚未支援迴圈遞迴查詢,和sqlserver、oracle相比,mysql難於在樹狀表中層層遍歷的子節點。本程式重點參考了下面的資料,寫了兩個sql儲存過程,子節點查詢算是照搬了,父節點查詢是逆思維弄的。
表結構和表資料就不公示了,查詢的表user_role,主鍵是id,每條記錄有parentid欄位(對應該記錄的父節點,當然,乙個父節點自然會有乙個以上的子節點嘛)
create function `getchildlist`(rootid int)
returns varchar(1000)
begin
declare schildlist varchar(1000);
declare schildtemp varchar(1000);
set schildtemp =cast(rootid as char);
while schildtemp is not null do
if (schildlist is not null) then
set schildlist = concat(schildlist,',',schildtemp);
else
set schildlist = concat(schildtemp);
end if;
select group_concat(id) into schildtemp from user_role where find_in_set(parentid,schildtemp)>0;
end while;
return schildlist;
end;
/*獲取子節點*/
/*呼叫: 1、select getchildlist(0) id; 2、select * 5from user_role where find_in_set(id, getchildlist(2));*/
create function `getparentlist`(rootid int)
returns varchar(1000)
begin
declare sparentlist varchar(1000);
declare sparenttemp varchar(1000);
set sparenttemp =cast(rootid as char);
while sparenttemp is not null do
if (sparentlist is not null) then
set sparentlist = concat(sparenttemp,',',sparentlist);
else
set sparentlist = concat(sparenttemp);
end if;
select group_concat(parentid) into sparenttemp from user_role where find_in_set(id,sparenttemp)>0;
end while;
return sparentlist;
end;
/*獲取父節點*/
/*呼叫: 1、select getparentlist(6) id; 2、select * from user_role where find_in_set(id, getparentlist(2));*/
Mysql 遞迴查詢子節點
查詢父編碼及以下所有子節點 select id from select t1.id,t1.parent id,if find in set t1.id,pids 0,pids,if find in set t1.parent id,pids 0,pids concat ws pids,id 0 as...
Oracle中的樹狀查詢 遞迴查詢
舉報資料庫中有乙個表,結構很簡單,如下所示 表名 tbinvoice 字段 id name parent id 每一行記錄表示乙個發票,parent id表示它的父物件id,假設現在表中有如下資料 id name parent id 1張三 2李四1 3王五1 4張一2 5王三2 6武松3 7李四4...
MySQL子查詢,聯結表
子查詢 select cust id from orders where order num in select order num from orderitems where prod id tnt2 對每個客戶執行count 計算,應該將count 作為乙個子查詢 select cust nam...