我有以下查询:
select distinct profile_id from userprofile_...
union
select distinct profile_id from productions_...
我将如何获得结果总数的计数?
我有以下查询:
select distinct profile_id from userprofile_...
union
select distinct profile_id from productions_...
我将如何获得结果总数的计数?
如果您想要所有记录的总数,那么您可以这样做:
SELECT COUNT(*)
FROM
(
select distinct profile_id
from userprofile_...
union all
select distinct profile_id
from productions_...
) x
Union All如果两个表中都有相等的行,则应该使用,因为 Union 会产生不同的
select count(*) from
(select distinct profile_id from userprofile_...
union ALL
select distinct profile_id from productions_...) x
在这种情况下,如果你在两个表中都得到相同Profile_Id的(id 可能是一个数字,所以它是可能的),那么如果你使用Union,如果你Id = 1在两个表中都有tables,你将丢失一行(它会出现一次而不是两次)
这将表现得很好:
select count(*) from (
select profile_id
from userprofile_...
union
select profile_id
from productions_...
) x
使用union保证不同的值 -union删除重复项,union all保留它们。这意味着您不需要distinct关键字(其他答案没有利用这一事实并最终做更多的工作)。
如果要计算每个中不同 profile_id 的总数,其中出现在两个表中的给定值被视为不同的值,请使用以下命令:
select sum(count) from (
select count(distinct profile_id) as count
from userprofile_...
union all
select count(distinct profile_id)
from productions_...
) x
此查询将胜过所有其他答案,因为数据库可以比联合列表更快地有效地计算表中的不同值。只需将sum()两个计数相加。
如果在 COUNT(*) 之一中结果等于 0,这些将不起作用。
这会更好:
选择总和(总计)
从
(
选择 COUNT(distinct profile_id) 作为总计
来自用户配置文件_...
联合所有
选择 COUNT(distinct profile_id) 作为总计
从制作_...
) X
正如 omg ponies 已经指出,在 UNION 中使用 distinct 是没有用的,你可以在你的情况下使用 UNION ALL .....
SELECT COUNT(*)
FROM
(
select distinct profile_id from userprofile_...
union all
select distinct profile_id from productions_...
) AS t1
最好的解决方案是添加两个查询结果的计数。如果表包含大量记录,这不会有问题。而且您不需要使用联合查询。前任:
SELECT (select COUNT(distinct profile_id) from userprofile_...) +
(select COUNT(distinct profile_id) from productions_...) AS total