programing

여러 테이블의 MYSQL 왼쪽 조인 카운트

lovecodes 2023. 8. 13. 10:46
반응형

여러 테이블의 MYSQL 왼쪽 조인 카운트

다른 테이블의 카운트를 나타내는 열을 추가하려고 합니다.

3개의 테이블이 있습니다.

메시지

MessageID    User      Message      Topic
1            Tom       Hi           ball
2            John      Hey          book
3            Mike      Sup          book
4            Mike      Ok           book

주제

Topic      Title     Category1    Category2
ball       Sports    Action       Hot
book       School    Study        Hot

별_지정됨

starID     Topic
1          ball
2          book
3          book
4          book

저는 다음과 같이 마무리하고 싶습니다.

주제_검토

Topic    Title     StarCount    UserCount    MessageCount
ball     Sports    1            1            1
book     school    3            2            3

따라서 기본적으로 고유한 값(각 주제 내에서 주어진 별 수, 주제 내에서 메시지를 가진 고유한 사용자 수, 각 주제 내에서 고유한 메시지 수)이 포함된 3개의 열을 첨부하고자 합니다.

최종적으로 범주(두 열 모두)도 필터링할 수 있습니다.

또한, 저는 최종적으로 제가 가입한 숫자를 기준으로 정렬하고 싶습니다.예를 들어, 오름차순으로 "별 수"를 정렬하거나 내림차순으로 "사용자 수"를 정렬하는 버튼을 사용합니다.

저는 다른 사람들의 답변을 조정하려고 노력했지만 제대로 작동하지 않습니다.

select
  t.Topic,
  t.Title,
  count(distinct s.starID) as StarCount,
  count(distinct m.User) as UserCount,
  count(distinct m.messageID) as MessageCount
from
  Topics t
  left join Messages m ON m.Topic = t.Topic
  left join Stars_Given s ON s.Topic = t.Topic
group by
  t.Topic,
  t.Title

SQL 피들

또는 하위 쿼리에서 집계를 수행할 수 있습니다. 이는 테이블에 상당한 양의 데이터가 있는 경우 더 효율적일 수 있습니다.

select
  t.Topic,
  t.Title,
  s.StarCount,
  m.UserCount,
  m.MessageCount
from
  Topics t
  left join (
    select 
      Topic, 
      count(distinct User) as UserCount,
      count(*) as MessageCount
    from Messages
    group by Topic
  ) m ON m.Topic = t.Topic
  left join (
    select
      Topic, 
      count(*) as StarCount
    from Stars_Given 
    group by Topic
  ) s ON s.Topic = t.Topic

SQL 피들

언급URL : https://stackoverflow.com/questions/15349189/mysql-left-join-counts-from-multiple-tables

반응형