pg(union all)统计总数count

在分页查询中,常用的一种做法是分两部分查询;第一部分用limit查询出需要的条数,第二步用count函数查询出总数;

sql1:  select t.id,t.create_by,t.create_date 
       from table t
       limit 0 offset 10

sql2 : select count(t.id) from talbe t

但是如果用到 union all 去查询结果集,在查询总数的时候就需要修改一下了,一般的思路是把union all 两端的数量字段统一,然后作为一个子表,执行sum(coun)就可以了;

大概是这样:

SELECT SUM	( tmpcount ) 
FROM
	(
    SELECT COUNT( t1.ID ) AS tmpcount 
    FROM	table t1 
     UNION ALL
    SELECT COUNT( t2.ID ) AS tmpcount 
    FROM w008_vedio_album t2
	) A

实际中用到的一种情境实例:

SELECT SUM
	( tmpcount ) 
FROM
	(
SELECT COUNT
	( A.ID ) AS tmpcount 
FROM
	w008_video_addr_info
	A LEFT JOIN sys_user s ON A.create_by = s.login_name
	LEFT JOIN w008_user_business_info info ON s.ID = info.sysuserid
	LEFT JOIN bpe_attach_file file ON A.ID = file.ID 
WHERE
	A.is_removed =0
	AND A.isshelves = 30 UNION ALL
SELECT COUNT
	( A.ID ) AS tmpcount 
FROM
	w008_vedio_album
	A LEFT JOIN sys_user s ON A.create_by = s.login_name
	LEFT JOIN w008_user_business_info info ON s.ID = info.sysuserid 
WHERE
	A.is_removed =0
	AND EXISTS (
SELECT
	rela.ID 
FROM
	w008_album_video_rela rela
	JOIN w008_video_addr_info addr ON rela.videoaddrinfo = addr.ID 
WHERE
	rela.vedioalbum = A.ID 
	AND addr.isshelves = 30 
	) 
	) A

结果:

pg(union all)统计总数count_第1张图片

 

 

 

你可能感兴趣的:(数据库)