dotnetcore / FreeSql

🦄 .NET aot orm, C# orm, VB.NET orm, Mysql orm, Postgresql orm, SqlServer orm, Oracle orm, Sqlite orm, Firebird orm, 达梦 orm, 人大金仓 orm, 神通 orm, 翰高 orm, 南大通用 orm, 虚谷 orm, 国产 orm, Clickhouse orm, DuckDB orm, TDengine orm, QuestDB orm, MsAccess orm.
https://freesql.net
MIT License
4.12k stars 857 forks source link

Potential performance bottleneck in AsTreeCte #1491

Open zsolt777 opened 1 year ago

zsolt777 commented 1 year ago

问题描述及重现代码:

First of all, thank you very much for this excellent library!!

In this recursive query I am interested only in two columns:

fsql.Select<TaskData>()
    .Where(a => a.ID == 23)
    .AsTreeCte(up: true)
    .ToList(p => new { p.ParentID, p.ID } );

This works as expected, but unfortunately inside the CTE in SQL all the columns are selected in both the anchor query and in the recursive query.

As you can see the 'Text', 'Due', etc. columns are selected unnecessarily, that can be a potential performance bottleneck when the table contains a lot of columns.

WITH [as_tree_cte]
as
(
SELECT 0 as cte_level, a.[ID], a.[ParentID], a.[PrevID], a.[Owner], a.[Text], a.[Style], a.[Due], a.[Created], a.[LastModification] 
FROM [Task] a 
WHERE (a.[ID] = 23)

union all

SELECT wct1.cte_level + 1 as cte_level, wct2.[ID], wct2.[ParentID], wct2.[PrevID], wct2.[Owner], wct2.[Text], wct2.[Style], wct2.[Due], wct2.[Created], wct2.[LastModification] 
FROM [as_tree_cte] wct1 
INNER JOIN [Task] wct2 ON wct2.[ParentID] = wct1.[ID]
)
SELECT a.[ParentID] as1, a.[ID] as2 
FROM [as_tree_cte] a

数据库版本

SQL Server 2019

安装的Nuget包

3.2.693

.net framework/. net core? 及具体版本

.NET 6.0

2881099 commented 1 year ago

ok, next version.