1

SQL サーバー データベースにクエリを実行する nhibernate を使用する Web サイトがあります。テーブルの 1 つには、次の列があります。

ID

ParentId

したがって、このテーブルの一部のエントリは次のようになります。

Id Name ParentId
1、「Joe」、3
3、「Tim」、5
5、「Jack」、7
7、「Tom」、null

このようなクエリを実行しようとしています (疑似 SQL) 。.

 "Select * from ThisTable where IsDescendant of 7"

これにより、 7 の子または children の子などが返されます。. (上記の例では、すべての行が返されます)

すべてをループに入れずにこれを修正する最善の方法は何ですか。また、私は nhibernate を使用しているので、これを関数としてコードに追加できますが、何百もの SQL ステートメントに変換されるようです。生のSQLでもこれを行う方法にも興味があります。

4

2 に答える 2

0

I suggest you create a table that holds the calculated descendants over multiple levels to all entries in the table you were referring. Using CTE should be quite effective, though if you query the descendants very often you can greatly reduce the databases overhead if you write out all descendance data in a seperate table that would have a structure like this:

Table XDescendance: ID, ItemID, ParentID, Level

You would then let this data be rewritten when a trigger on that table notices any changes.

Then you can query this almost exactly as you wrote it (well almost)

SELECT DISTINCT
        ThisTable.*
    FROM ThisTable
    INNER JOIN XDescendance
        ON ThisTable.ID = XDescendance.ItemID
        AND XDescendance.ParentID = 7
于 2013-03-21T08:37:44.933 に答える
0

SQLServer2005+ では、再帰 CTE を使用できます

DECLARE @Id int = 7     
;WITH cte AS
  (
   SELECT Id, Name, ParentId
   FROM dbo.test45
   WHERE Id = @Id
   UNION ALL
   SELECT t.Id, t.Name, t.ParentId
   FROM dbo.test45 t JOIN cte c On t.ParentId = c.Id
   )
   SELECT *
   FROM cte

SQLFiddle のデモ

于 2013-03-21T08:30:48.033 に答える