SQLはツリータイプのすべての下級またはすべての上級者を読みだします。

6527 ワード

プログラミングまたは構築においては、ツリー型のノードに従って、そのすべての上位または下位を読み取る必要がある場合がしばしばある。ツリーウィジェットに結合して表示します。Oracleでは、start with…connect by pror…で実現できます。具体的な書き方は:下級を調べる:
select * from sa_dept_dict start with dept_id=2170 connect by prior dept_ID=upper_id order by SORT_ORDER
検索下位:
select * from sa_dept_dict start with dept_id=2170 connect by prior upper_id=dept_ID order by SORT_ORDER
SQL SERVERではやや複雑です。With....AS...文を使う必要があります。この文はサブクエリとも言われています。いろいろなことをさせてSQLの断片を定義します。SQLの断片はSQL文全体で使われます。場合によっては、SQL文の可読性を高くするために、ユニオンALLの異なる部分でデータを提供する部分として利用することもあります。私たちはwithでunionを結合して、ツリー型の上司と部下を調べます。
検索下位:
with tree as (select * from sa_dept_dict where dept_id=2016 union all 
select a.* from sa_dept_dict as a,tree as b where b.dept_id=a.upper_id ) select * from tree order by sort_order
クエリの上位:
with tree as (select * from sa_dept_dict where dept_id=2016 union all 
select a.* from sa_dept_dict as a,tree as b where a.dept_id=b.upper_id ) select * from tree order by sort_order
 
原文の出所:http://bbs.delit.cn/thread-132-1-1.html 転載は出典を明記してください。執筆者:計量科学技術 http://www.delit.cn