mysql級聯查詢

2021-08-08 07:02:19 字數 1411 閱讀 2074

實現效果 例如:  中國 下的 省 市 縣 鄉 

輸入 省的id 能把該省下的市,縣,鄉全部查出來,輸入該市的id 可以把 該市下的 縣,鄉全部查出來

oracle 級聯查詢:oracle有內建函式  start with ...connect by prior 直接實現級聯效果如

select a.* from t_depart  a start with depid='213520' connect by prior depid=pdepid

depid是指 部門編號, pdepid是指上級部門編號   depid='213520'  是指查遞迴depid=213520的部門即查出 depid

是213520

的子節點,孫節點,重孫節點,......

不過在mysql 中就有點麻煩了,得建立方法,並呼叫:

mysql中:建立function:

delimiter $$

use `device`$$

drop function if exists `getchildlist`$$

create definer=`root`@`localhost` function `getchildlist`(rootid varchar(100)) returns varchar(1000) charset utf8

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(depid) into ctemp from t_depart

where find_in_set(pdepid,ctemp)>0;

end while;  

return ptemp;

end$$

delimiter ;

通過 

select getchildlist('

213520

') from dual 可以驗證查出 id是

213520

及它以下節點的id 例如 我的結果是 $,

213520,213520

12,21352013

通過select * from 『

t_depart

』 where find_in_set (depid,getchildlist('

213520

'));

就會查出

t_depart

這個表中, id = '213520' 及其子孫節點的詳細資訊。

mysql不支援級聯查詢 mysql級聯查詢

實現效果 例如 中國 下的 省 市 縣 鄉 輸入 省的id 能把該省下的市,縣,鄉全部查出來,輸入該市的id 可以把 該市下的 縣,鄉全部查出來 oracle 級聯查詢 oracle有內建函式 start with connect by prior 直接實現級聯效果如 select a.from t...

mysql 級聯優化 MySQL級聯查詢的優化

一 php的foreach和mysql的in哪個執行效率高?1 foreach item as k v 迴圈100次 這裡使用單id查詢一條資料。2 使用in查詢id in 1,2,3,100 100個id條件。同樣的結果,1個查詢100次,1次查詢1條資料 乙個查詢1次,1次查詢100條資料,哪乙...

oracle級聯查詢

今天學習oracle 學到了乙個級聯語句 select from table start with 條件1 connect by prior 條件2 where 條件3例 select from usertable start with parent id 1 connect by prior or...