子查询问题 返回
实体表和视图表的连接查询,本来使用的左连接查询,但是两表数据比较多,而且连接字段都非主键,导致查询查询速度缓慢,于是想着换成子查询来获取右表,但是我根据教程写的语句,使用时报错“
当前表达式Subqueryable().Where(right => ((left.name == right.Name) AndAlso (left.type == right.Type))).First().Price 不支持,查看导航是否配置正确等或者缺少Includes()
”,具体代码和两表实体为
public class a { [SugarColumn(ColumnName = "id", ColumnDataType = "int", IsPrimaryKey = true, IsIdentity = true)] public int Id { get; set; } [SugarColumn(ColumnName = "cId", ColumnDataType = "int", IsNullable = true)] public int? cId { get; set; } [SugarColumn(ColumnName = "name", ColumnDataType = "nvarchar", IsNullable = true)] public string? name { get; set; } [SugarColumn(ColumnName = "type", ColumnDataType = "nvarchar", IsNullable = true)] public string? type { get; set; } [SugarColumn(ColumnName = "qty", ColumnDataType = "real", IsNullable = true)] public float? Qty { get; set; } [Navigate(NavigateType.OneToOne, nameof(cId), nameof(c.Id))] public c? cInfo { get; set; } [SugarColumn(IsIgnore = true)] public float? price { get; set; } } public class b { [SugarColumn(ColumnName = "id", ColumnDataType = "int")] public int Id { get; set; } [SugarColumn(ColumnName = "name", ColumnDataType = "nvarchar", IsNullable = true)] public string? Name { get; set; } [SugarColumn(ColumnName = "type", ColumnDataType = "nvarchar", IsNullable = true)] public string? Type { get; set; } [SugarColumn(ColumnName = "price", ColumnDataType = "real", IsNullable = true)] public float? Price { get; set; } } ISugarQueryable<left> list = SqlSugarBase.QYDB.Queryable<left, right> ((left, right) => new JoinQueryInfos(JoinType.Left, left.name == right.Name && left.type == right.Type)) .Select(left => new left { Id = left.Id, name = left.name, type = left.type, Qty = left.Qty, price = SqlFunc.Subqueryable<right>().Where(right => left.name == right.Name && left.type == right.Type).First().Price }).MergeTable();
热忱回答(9)
-
娇娇欲静 VIP02周前
另外,教程都是一次性获取两表数据,连接查询完成后才能进行其他查询,但需求中有根据左表字段进行查询的查询字段,还会有分页查询,是否能左表查询完成后再与右表进行子连接查询?左表查询条件不定,不能写在JoinQueryInfos中
0 回复 -
娇娇欲静 VIP02周前
左连接查询,有分页的时候挺快的,但是如果没分页,或者连接查询后再分页(需要对右表进行查询),都很慢,需要3分钟起步
0 回复 -
娇娇欲静 VIP02周前
主楼的问题,我把
SqlFunc.Subqueryable<right>().Where(right => left.name == right.Name && left.type == right.Type).First().Price
改成
SqlFunc.Subqueryable<right>().Where(right => left.name == right.Name && left.type == right.Type).Select(s => s.Price)
就好了,但是查询实在太慢了,可以先左表查询、分页完成再子查询吗?
0 回复 -
fate sta VIP02周前
@娇娇欲静:
AOP 监控SQL去分析 ,先确SQL是否慢
0 回复 -
fate sta VIP02周前
还有这个.MergeTable(); 是做什么的
0 回复 -
娇娇欲静 VIP02周前
先左表查询、分页完成再子查询也搞出来了,但是右表数据可能也太大了,子查询比左连接查询更慢了,我再想想怎么办吧
0 回复 -
娇娇欲静 VIP02周前
@fate sta:我该回用左连接,不用子查询了,监控后就是SQL慢
0 回复 -
娇娇欲静 VIP02周前
@fate sta:后续分页可能要分页,所以加了.MergeTable()
0 回复 -
fate sta VIP02周前
@娇娇欲静:sql慢就优化生成的SQL,用sqlsugar就是sql思维 ,你想生成什么样的SQL就用什么样的写法
0 回复