这是我的疑问:
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
中返回10行,这些行匹配搜索字符串" a"。使用offset / fetch,我可以轻松地在我的应用程序中进行分页。但我还需要知道的是,数据库中有多少行匹配搜索字符串" a"没有获取限制。
我的第一个方法是结果查询count(*)
,但这不起作用(因为我猜的是联盟)。
答案 0 :(得分:0)
最好在提供VIEW
查询的情况下创建UNION
。然后,您可以COUNT(*)
记录并进一步显示前面的
答案 1 :(得分:0)
你可以尝试在你选择*语句中添加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