유니언 쿼리를 카운트하는 방법
다음 질문이 있습니다.
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
'source' 카테고리의 다른 글
ReadableStream 개체에서 데이터를 검색하시겠습니까? (0) | 2022.10.23 |
---|---|
python 내에서 명령줄 프로그램 실행 (0) | 2022.10.23 |
MySQL의 현재 시간대를 얻으려면 어떻게 해야 합니까? (0) | 2022.10.14 |
Python/Json:큰따옴표로 둘러싸인 속성 이름이 필요합니다. (0) | 2022.10.14 |
Jest vue-multicelect에서 vuex 작업을 테스트할 때 모의 함수가 호출되어야 합니다. (0) | 2022.10.14 |