1、如下图,c.industryId作为string类型当作参数传递,解析时会加单引号,即:”c.industryId“,
生成的查询语句就会变成
-- 这里把'c.IndustryGroup' 当成实际的值所以会查询不出数据
select b.`Name`,COUNT(c.Id) Num
from base_industry_dist b
LEFT JOIN base_companyinfo c on b.Id='c.IndustryGroup'
Where b.Deep=0 GROUP BY b.Id ORDER BY num
可修改成如下:
--使用$语法糖的写法可读性高,代码简洁
/// <summary>
/// 获取产业所属企业数量统计
/// </summary>
/// <param name="id"></param>
/// <param name="deep"></param>
/// <returns></returns>
public async Task<List<IndustryCompanyStatistictQto>> GetIndustryCompanyStatistictsAsync(Guid? id, int deep)
{
var sqlStr = @$"select b.`Name`,COUNT(c.Id) Num
from base_industry_dist b ";
var whereStr = @" Where b.Deep=@deep";
var groupByStr = @" GROUP BY b.Id ORDER BY Num desc";
var industryId = "c.IndustryGroup";
var sqlPredicates = new List<string>();
var queryParam = new DynamicParameters();
queryParam.Add(nameof(deep), deep);
if (deep == 1)
{
industryId = "c.IndustrySubGroup";
sqlPredicates.Add(" b.ParentId=@parentId");
queryParam.Add("parentId", id.Value);
}
else if (deep == 2)
{
industryId = "c.IndustrySpecific";
sqlPredicates.Add(" b.ParentId=@parentId");
queryParam.Add("parentId", id.Value);
}
else
{
queryParam.Add(nameof(industryId), industryId);
}
var leftJoinStr = @$" LEFT JOIN base_companyinfo c on b.Id={industryId}";
sqlStr += leftJoinStr;
sqlStr += whereStr;
if (sqlPredicates.Any())
{
var sqlPredicatesStr = sqlPredicates.Aggregate((p, n) => $"{p} and {n}");
sqlStr = @$"{sqlStr}
and {sqlPredicatesStr}";
}
sqlStr += groupByStr;
var connect = await GetDbConnectionAsync();
var dbTransaction = await GetDbTransactionAsync();
//var tt = (await connect.QueryAsync(sqlStr, queryParam, dbTransaction)).ToList();
return (await connect.QueryAsync<IndustryCompanyStatistictQto>(sqlStr, queryParam, dbTransaction)).ToList();
}