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

分表查询被指定最后一个表名 #1945

Open
peng951 opened this issue Dec 10, 2024 · 3 comments
Open

分表查询被指定最后一个表名 #1945

peng951 opened this issue Dec 10, 2024 · 3 comments

Comments

@peng951
Copy link

peng951 commented Dec 10, 2024

问题描述及重现代码:

我需要实现查询多分表,SQL类似以下:
select * from table202412
union all
(
select * from table202411
)
........;
有以下代码实现:
ISelect select = null;
while (searchDate <= paraModel.QueryDate)
{
string tableName = $"public.{nameof(AttendanceRecord).ToLower()}{searchDate.Year * 100 + searchDate.Month}";
if (_freesql.DbFirst.ExistsTable(tableName))
{
tableNames.Add(tableName);
var lastselect = _freesql.Select()
.AsTable((t, s) => tableName)
;
if (select is null)
select = lastselect;
else
select = select.UnionAll(
lastselect
);
}
searchDate = searchDate.AddMonths(1);
}
当我的tablename在while循环里面显示定义的时候,可以达到我上述的查询目的。
当我的tablename在外部定义的时候,得到的SQL语句如下:
select * from table202412
union all
(
select * from table202412
)
..。。。
最终导致我只能查询一个分表的数据。

// c# code

数据库版本

pg13

安装的Nuget包

3.2.680

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

netcore

@2881099
Copy link
Collaborator

2881099 commented Dec 12, 2024

看不太明白,如果不够用可以考虑用 WithTempQuery + UnionAll

@peng951
Copy link
Author

peng951 commented Dec 13, 2024

可以试试一下这两段代码:
第一段:
ISelect select = null;
while (searchDate <= paraModel.QueryDate)
{
string tableName = $"public.{nameof(AttendanceRecord).ToLower()}{searchDate.Year * 100 + searchDate.Month}";
if (_freesql.DbFirst.ExistsTable(tableName))
{
tableNames.Add(tableName);
var lastselect = _freesql.Select()
.AsTable((t, s) => tableName)
;
if (select is null)
select = lastselect;
else
select = select.UnionAll(
lastselect
);
}
searchDate = searchDate.AddMonths(1);
}
var sql=select is not null?select.ToSql():string.Empty;

第二段:
ISelect select = null;
string tableName=string.Empty;
while (searchDate <= paraModel.QueryDate)
{
tableName = $"public.{nameof(AttendanceRecord).ToLower()}{searchDate.Year * 100 + searchDate.Month}";
if (_freesql.DbFirst.ExistsTable(tableName))
{
tableNames.Add(tableName);
var lastselect = _freesql.Select()
.AsTable((t, s) => tableName)
;
if (select is null)
select = lastselect;
else
select = select.UnionAll(
lastselect
);
}
searchDate = searchDate.AddMonths(1);
}
var sql=select is not null?select.ToSql():string.Empty;
针对pgsql数据库,按月分表(查询两个及以上分表)。你把这个tosql一下就可以看出来了。

@2881099
Copy link
Collaborator

2881099 commented Dec 13, 2024

要不提供完整一下完整的 console.csproj 项目。

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