Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

子查询生成SQL语句错误 #1201

Closed
LeaFrock opened this issue Aug 2, 2022 · 5 comments
Closed

子查询生成SQL语句错误 #1201

LeaFrock opened this issue Aug 2, 2022 · 5 comments

Comments

@LeaFrock
Copy link

LeaFrock commented Aug 2, 2022

问题描述及重现步骤:

代码如下:

// 接口参数request包含Id和ClassIds两个属性。
var count = await FreeSql.Select<ClassStudent>()
                .Where(p => request.ClassIds.Contains(p.ClassId) 
                    && !FreeSql.Select<TestAnswer>().Any(a => a.TestID == request.Id && a.StudentNo == p.StudentNo))
                .CountAsync();

实际生成的SQL:

SELECT count(1) as1 
FROM [ClassStudent] a 
WHERE (((a.[ClassId]) in (1,2,3)) AND not(exists(SELECT TOP 1 1 
    FROM [TestAnswer] a 
    WHERE (a.[TestID] = 1 AND a.[StudentNo] = a.[StudentNo]))))

经过多次尝试,发现似乎跟Any()表达式里的参数名有关,修改为ta => ...后正常。

SELECT count(1) as1 
FROM [ClassStudent] a 
WHERE (((a.[ClassId]) in (1,2,3)) AND not(exists(SELECT TOP 1 1 
    FROM [TestAnswer] ta 
    WHERE (ta.[TestID] = 1 AND ta.[StudentNo] = a.[StudentNo]))))

这种参数名导致的问题感觉挺奇怪的,也没看到文档里有特殊提示。EF Core不会有这种问题。

数据库的具体版本

SQL Server 2012

安装的包

3.2.665

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

.NET 6
@2881099
Copy link
Collaborator

2881099 commented Aug 2, 2022

确实会有这个问题,属于已知。

别名规则比较复杂,因为别名默认 a 的原因,回头看怎么优化一下。

优化好了在这个帖子通知。

@LeaFrock
Copy link
Author

LeaFrock commented Aug 2, 2022

EF Core似乎从未遇到类似的问题,可以参考一下实现。
通常表名首字母+数字序号作为表别名,可以避免开发者在表达式中碰撞到(很少会有人写成t1 => ....)。

@2881099
Copy link
Collaborator

2881099 commented Aug 2, 2022

实际我们多表比 ef 考虑的场景更多,别名规则几年了一直不想再碰。

我抽空再专门处理这个问题吧,群不定时有人反馈这个问题。

最好的维护方式之一,就是从源头杜绝问题。

@LeaFrock
Copy link
Author

LeaFrock commented Aug 2, 2022

最好的维护方式之一,就是从源头杜绝问题

👍 的确。期待修复。

@2881099
Copy link
Collaborator

2881099 commented Aug 2, 2022

v3.2.666-preview20220805

版本已发布,单元测试全部通用。

解决方法:

判断子查询别名,若与 Parent 同名,则将 alias 变成 sub_x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants