How to do a count on a union query

前端 未结 6 1038
谎友^
谎友^ 2020-12-28 12:32

I have the following query:

select distinct profile_id from userprofile_...

union

select distinct profile_id from productions_...

How wou

6条回答
  •  一生所求
    2020-12-28 13:04

    This will perform pretty well:

    select count(*) from (
        select profile_id
        from userprofile_...
        union
        select profile_id
        from productions_...
    ) x
    

    The use of union guarantees distinct values - union removes duplicates, union all preserves them. This means you don't need the distinct keyword (the other answers don't exploit this fact and end up doing more work).

    Edited:

    If you want to total number of different profile_id in each, where given values that appear in both table are considered different values, use this:

    select sum(count) from (
        select count(distinct profile_id) as count
        from userprofile_...
        union all
        select count(distinct profile_id)
        from productions_...
    ) x
    

    This query will out-perform all other answers, because the database can efficiently count distinct values within a table much faster than from the unioned list. The sum() simply adds the two counts together.

提交回复
热议问题