I have to create a ranking of the directors who have made the most reviews. What is the method for reordering according to the number of rows in another table?
Table 1 (director)
+-------------+--------------+ | name | company | +-------------+--------------+ | John | John SPA | | Mark | Marks Food | | Patrick | Patrick & CO | +-------------+--------------+
Table 2 (employee_reviews)
+-------------+--------------+----------+---------+ | director | employee | Text | Stars | +-------------+--------------+----------+---------+ | John | Omar | ... | 3 | | John | Richard | ... | 5 | | Mark | Simon | ... | 5 | | Patrick | David | ... | 1 | | Patrick | Omar | ... | 2 | | John | Simon | ... | 4 | +-------------+--------------+----------+---------+
Result (Directors ranking):
1st) Dir. John [3 reviews] 2nd) Dir. Patrick [2 reviews] 3rd) Dir. Mark [1 review] ...
Advertisement
Answer
You need to join to your table and select the count when (ON) the author equals the director, then you group the rows by the director results, and then you order it.
Example: SELECT *, COUNT(reviews.id) FROM directors JOIN reviews ON reviews.author = directors.director GROUP BY direcotrs.director ORDER BY COUNT(reviews.id) DESC;