如何对联合查询进行计数

Dav*_*542 35 mysql sql union aggregate-functions

我有以下查询:

select distinct profile_id from userprofile_...

union

select distinct profile_id from productions_...
Run Code Online (Sandbox Code Playgroud)

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

Tar*_*ryn 63

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

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

    union all

    select distinct profile_id 
    from productions_...
) x
Run Code Online (Sandbox Code Playgroud)

  • 考虑到我先发布了它,而我没有编辑我的答案,至少这真的很不公平!:( (2认同)

Gon*_*o.- 17

Union All如果两个表中都有等于行的话,你应该使用它,因为Union是一个独特的行

select count(*) from 
(select distinct profile_id from userprofile_...

union ALL

select distinct profile_id from productions_...) x
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果你Profile_Id在两个表中都有相同的内容(id可能是一个数字,那么它是可能的),那么如果你使用它Union,如果你Id = 1同时使用tables,你将丢失一行(它将出现一次而不是两次)


Boh*_*ian 8

这将表现得很好:

select count(*) from (
    select profile_id
    from userprofile_...
    union
    select profile_id
    from productions_...
) x
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

此查询将超出所有其他答案,因为数据库可以比联合列表更快地有效地计算表中的不同值.在sum()简单地增加了两项罪名在一起.


Aka*_* KC 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 
Run Code Online (Sandbox Code Playgroud)


小智 5

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

SELECT (select COUNT(distinct profile_id) from userprofile_...) + 
(select COUNT(distinct profile_id) from productions_...) AS total
Run Code Online (Sandbox Code Playgroud)


小智 5

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

这样会更好:

SELECT SUM(总计)
从
(
    选择 COUNT(distinct profile_id) AS 总计
    从用户资料_...

    联合所有

    选择 COUNT(distinct profile_id) AS 总计
    从生产_...
) X