与 SQL Server 联合的分页
Posted
技术标签:
【中文标题】与 SQL Server 联合的分页【英文标题】:Pagination over union with SQL Server 【发布时间】:2014-11-26 10:05:39 【问题描述】:这是我的查询:
select * from (
select u.id, 'u' as [type], u.firstName, u.lastName, c.name as companyName,
u.lastName + u.firstName + isNull(c.name, '') as sortName
from users as u
left outer join companies as c on c.id = u.company_id
union all
select id, 'c' as [type], null as firstName, null as lastName, name as
companyName, name as sortName
from companies
) as result
where sortName like '%a%'
order by sortName
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
它从表users
和companies
返回与搜索字符串“a”匹配的10 行。通过偏移/获取,我可以轻松地在我的应用程序中进行分页。但我仍然需要知道的是,数据库中有多少行与搜索字符串“a”匹配而没有获取限制。
我的第一种方法是在结果查询上使用count(*)
,但这不起作用(我猜是因为联合)。
【问题讨论】:
为什么说使用COUNT(*) OVER()
不起作用?这应该在这个查询中起作用----SELECT object_id, Count = COUNT(*) OVER() FROM (SELECT * FROM sys.all_objects UNION ALL SELECT * FROM sys.all_objects) AS t WHERE t.Name LIKE 's%' ORDER BY object_id OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;
----计数是正确的
我在没有 over()
的情况下使用了 count(*)
,但这不起作用。感谢您的帮助!
啊,我看错了你的问题。乐于助人:)
【参考方案1】:
最好使用提供的UNION
查询创建VIEW
。然后你可以COUNT(*)
记录并进一步显示给前台
【讨论】:
【参考方案2】:您可以尝试在 select * 语句中添加 COUNT(*) OVER(),如下所示。在下面的示例中,总行数将位于名为“total_rows”的新列中。
select *, total_rows=COUNT(*) OVER() from (
select u.id, 'u' as [type], u.firstName, u.lastName, c.name as companyName,
u.lastName + u.firstName + isNull(c.name, '') as sortName
from users as u
left outer join companies as c on c.id = u.company_id
union all
select id, 'c' as [type], null as firstName, null as lastName, name as
companyName, name as sortName
from companies
) as result
where sortName like '%a%'
order by sortName
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
【讨论】:
以上是关于与 SQL Server 联合的分页的主要内容,如果未能解决你的问题,请参考以下文章