【发布时间】:2012-07-28 17:17:28
【问题描述】:
我有以下疑问:
select distinct profile_id from userprofile_...
union
select distinct profile_id from productions_...
如何计算结果总数?
【问题讨论】:
标签: mysql sql union aggregate-functions
我有以下疑问:
select distinct profile_id from userprofile_...
union
select distinct profile_id from productions_...
如何计算结果总数?
【问题讨论】:
标签: mysql sql union aggregate-functions
如果您想要所有记录的总数,那么您可以这样做:
SELECT COUNT(*)
FROM
(
select distinct profile_id
from userprofile_...
union all
select distinct profile_id
from productions_...
) x
【讨论】:
如果两个表中都有相等的行,你应该使用Union All,因为联合使一个不同的
select count(*) from
(select distinct profile_id from userprofile_...
union ALL
select distinct profile_id from productions_...) x
在这种情况下,如果你在两个表中都有相同的Profile_Id(id 可能是一个数字,所以这是可能的),那么如果你使用Union,如果你在两个tables 中都有Id = 1,你会丢失一排(它会出现一次而不是两次)
【讨论】:
这会表现得很好:
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) AS 总计 来自用户配置文件_... 联合所有 选择 COUNT(distinct profile_id) AS 总计 从制作_... ) 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
【讨论】:
UNION 上是没有用的 - 只有UNION ALL 才需要。可能不想复制别人的答案;)
最好的解决方案是添加两个查询结果的计数。如果表包含大量记录,这不会有问题。而且您不需要使用联合查询。 例如:
SELECT (select COUNT(distinct profile_id) from userprofile_...) +
(select COUNT(distinct profile_id) from productions_...) AS total
【讨论】: