SQL >> Database teknologi >  >> RDS >> Mysql

Optællinger på tværs af flere tabeller med LEFT JOIN

Du kan hente flere counts i én forespørgsel med distinct:

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

Ved store tabeller er subqueries ofte hurtigere:

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
  1. Skrivning af et MySQL INNER JOIN på tværs af flere tabeller

  2. Join tre MySQL-tabeller med et many-to-many-brou

  3. Slet rækker fra flere tabeller i MySQL

  4. MySQL SELECT fra tabeller baseret på flere rækker