如何对联合查询进行计数

时间:2012-07-31 00:45:16

标签: mysql sql union aggregate-functions

我有以下查询:

select distinct profile_id from userprofile_...

union

select distinct profile_id from productions_...

我如何获得结果总数的计数?

6 个答案:

答案 0 :(得分:60)

如果您想要所有记录的总计数,那么您可以这样做:

SELECT COUNT(*)
FROM
(
    select distinct profile_id 
    from userprofile_...

    union all

    select distinct profile_id 
    from productions_...
) x

答案 1 :(得分:17)

如果两个表中都有等于行的话,你应该使用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 = 1tables中,您将丢失一行(它将显示一次而不是两次)

答案 2 :(得分:8)

这将表现得很好:

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()只是将两个计数加在一起。

答案 3 :(得分:5)

由于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 

答案 4 :(得分:3)

最佳解决方案是添加两个查询结果的计数。如果表包含大量记录,则不会出现问题。而且您不需要使用联合查询。 例如:

SELECT (select COUNT(distinct profile_id) from userprofile_...) + 
(select COUNT(distinct profile_id) from productions_...) AS total

答案 5 :(得分:3)

如果在COUNT(*)之一中结果等于0,则这些将不起作用。

这会更好:

SELECT SUM(total)
FROM
(
    select COUNT(distinct profile_id) AS total
    from userprofile_...

    union all

    select COUNT(distinct profile_id) AS total
    from productions_...
) x