source

유니언 쿼리를 카운트하는 방법

factcode 2022. 10. 14. 22:39
반응형

유니언 쿼리를 카운트하는 방법

다음 질문이 있습니다.

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두 표에 동일한 행이 있는 경우 유니언은 구별을 하기 때문에

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행이 1개 없어집니다(이 행은 2개가 아닌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일 경우 이 값은 작동하지 않습니다.

이것이 더 나을 것입니다.

SELECT SUM(합계)부터(COUNT(distinct profile_id) AS 합계를 선택합니다.userprofile_에서...

모두 합치다
COUNT(distinct profile_id) AS 합계를 선택합니다.프로덕션에서...
) x

oomg pornes는 이미 UNION과 구별하여 사용할 필요가 없다고 지적했으므로, 당신의 경우 UNION ALL을 사용할 수 있습니다.

SELECT COUNT(*) 
FROM 
( 
select distinct profile_id from userprofile_...
union all
select distinct profile_id from productions_...
) AS t1 

최선의 해결책은 2개의 쿼리 결과 수를 추가하는 것입니다.테이블에 다수의 레코드가 포함되어 있으면 문제가 되지 않습니다.그리고 당신은 유니온 쿼리를 사용할 필요가 없습니다.예:

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

언급URL : https://stackoverflow.com/questions/11731655/how-to-do-a-count-on-a-union-query

반응형