2016-08-28 4 views
1

user이 얼마나 많은지 conversations 개를 닫고 각 user 개가 얼마나 많은지 개를 써야하는지 계산하고 싶습니다.연결 수를 계산 중

user는이 많은 conversations

conversations이 가진 messageuser

이 속할 수 있습니다 messages

가 좀 멀리

select a.id, u.display_name, count(c.id) as closed, count(m.id) as replied 
from apps a 
left join app_users au on au.app_id = a.id 
left join users u on u.id = au.user_id 
left join conversations c on c.app_id = a.id and c.closed_by_id = u.id 
left join messages m on m.conversation_id = c.id and m.user_id = u.id 
group by a.id, u.id 
order by closed desc 

있어 질의입니다 많은 내가 메시지에 가입하지 않으면 잘 작동합니다. 그냥 닫힌 대화를 계산. 메시지를 결합 할 때 closedreplied 열은 정확히 같은 번호입니다 (두 가지 모두에 대해서도 올바르지 않습니다)

아이디어가 있으십니까?

+0

은'수 (별개의 c.id)'이 될 수 있습니까? – Mike

+0

메시지가 '폐쇄'또는 '응답 됨'상태라는 열이 있습니까? –

+0

아니요,하지만 'closed_at'이 있고 메시지의'user_id '가 계산중인 사용자와 일치하는 경우 사용자가 메시지에 회신했습니다. – Tarlen

답변

0

더러운 빠른 및-솔루션은 count(distinct)을 사용하는 것입니다 :이 많은 상황에서 작동합니다

select a.id, u.display_name, 
     count(distinct c.id) as closed, count(distinct m.id) as replied 

. 그러나 "폐쇄 형"및 "응답 형"이 많으면 중간 계산이 상당히 커서 성능에 영향을 미칠 수 있습니다. 이것이 문제인 경우 조인 전에 결과를 사전 집계하여 해결하십시오.

1

당신은 가입하기 전에 하위 쿼리에서 계산 수행 할 수 있습니다

select a.id, u.display_name, c.closed, m.replied 
from apps a 
left join app_users au on au.app_id = a.id 
left join users u on u.id = au.user_id 
left join lateral (
    select id, count(*) as closed 
    from conversations 
    where closed_by_id = u.id) c on c.app_id = a.id 
left join lateral (
    select count(*) as replied 
    from messages 
    where user_id = u.id) m on m.conversation_id = c.id 
order by c.closed desc; 
+0

app_id 및 display_name별로 그룹화하지 않습니다. 만약 내가 이것들을위한 그룹을 추가한다면, 그것은 또한'closed'와'replied'에 대한 그룹을 원하지만, 이것은 말이되지 않습니다. – Tarlen

관련 문제