mysql 中沒有支援遞迴的查詢,自行編寫函式實現。
如資料庫裡有部門表dept,欄位有id、name、pid
create table dept(
id int(11) not null,
name varchar(20),
pid int(11) not null,
primary key(id)
);
插入資料:
insert into dept(id,name,pid) values(1,'a',0);
insert into dept(id,name,pid) values(2,'b',0);
insert into dept(id,name,pid) values(3,'a1',1);
insert into dept(id,name,pid) values(4,'a2',1);
insert into dept(id,name,pid) values(5,'a11',3);
insert into dept(id,name,pid) values(6,'a21',4);
insert into dept(id,name,pid) values(7,'a22',4);
查詢:
select * from dept;
+----+------+-----+
| id | name | pid |
+----+------+-----+
| 1 | a | 0 |
| 2 | b | 0 |
| 3 | a1 | 1 |
| 4 | a2 | 1 |
| 5 | a11 | 3 |
| 6 | a21 | 4 |
| 7 | a22 | 4 |
+----+------+-----+
編寫函式:
create function `getchild`(rootid varchar(36)) returns varchar(1000)
begin
declare ptemp varchar(1000);
declare ctemp varchar(1000);
set ptemp = '#';
set ctemp = rootid;
while ctemp is not null do
set ptemp = concat(ptemp, ',', ctemp);
select group_concat(id)
into ctemp
from dept
where find_in_set(pid, ctemp) > 0;
end while;
return ptemp;
end
自定義函式說明:引數rootid為指定門店id,ptemp為最終返回變數,ctemp為中間變數,最終返回是「#,1,2」格式的字串。
JS實現 查詢指定父節點下所有子代節點
利用js遍歷出某個父節點下的所有子節點,深度優先遍歷,每一次都優先遍歷子節點,所有子節點遍歷完,才返回遍歷兄弟節點 第一種方式是利用遞迴將指定父節點下的所有子節點,但該方式空間占有率較高,耗時長 function getchildren parent 找body下面的所有子代節點 getchildr...
mysql 查詢父級
mysql遞迴查詢,mysql中從子類id查詢所有父類 做無限分類經常用到 由於mysql 不支援類似 oracle with connect的 遞迴查詢語法 之前一直以為類似的查詢要麼用儲存過程要麼只能用程式寫遞迴查詢.現在發現原來一條sql語句也是可以搞定的 先來看資料表的結構如下 id nam...
MySql遞迴查詢父級 子級資料
1.根據父級id遞迴查詢所有下級id select id from select t1.id,if find in set t1.parent id,pids 0,pids concat pids t1.id 0 as ischild from select id,parent id from ta...