Question

I have a movie database with a table for actors and another one for movies, I created a third table to add an actor partecipation in a movie. I added a field "star" to distinque leading actors from not leading actors. I wish create a list order by the actors importance and so by the the total number of "stars".

SELECT a.id, a.name, COUNT( p.star ) AS star
FROM actors a
JOIN playing p, movies m
WHERE p.id_actor = a.id
AND p.id_movie = m.id
AND p.star =1
GROUP BY p.star
ORDER BY p.star DESC;

ACTORS

+----+---------+
| id |  name   |
+----+---------+
|  1 | actor01 |
|  2 | actor02 |
|  3 | actor03 |
+----+---------+

MOVIES

+----+----------+
| id |  title   |
+----+----------+
|  1 | movie01  |
|  2 | movie02  |
|  3 | movie03  |
+----+----------+

PLAYING

+----------+----------+-------+------+
| id_movie | id_actor | char  | star |
+----------+----------+-------+------+
|        1 |        1 | char1 |    0 |
|        1 |        2 | char2 |    1 |
|        2 |        3 | char3 |    1 |
+----------+----------+-------+------+

I Need output Like:

+----------+--------------+
|    actor |  protagonist |
+----------+--------------+
|  actor01 |    2 times   |
|  actor02 |    3 times   |
+----------+--------------+
Was it helpful?

Solution

You need to fix the group by clause to group by the actor not the star column. You need to fix the order by to group by the aggregated column, not the original column:

SELECT a.id, a.name, sum( p.star = 1) AS stars
FROM actors a join playing p
     on p.id_actor = a.id join
     movies m
     on p.id_movie = m.id
GROUP BY a.id, a.name
ORDER BY stars DESC;

Along the way, I fixed the from so it uses proper join syntax (with an on clause). And changed the query so it returns all actors, even those who have never been the star.

OTHER TIPS

1.If you want to count all stars for an actor, you should group by actor but not stars.(Unless you want to count how many times an actor gets 1 star in a movie, you may not want to group by star)

2.You may want to use ON with JOIN

3.You may want to ORDER BY star but not ORDER BY p.star since you want to order by the result.

4.You may want to use SUM instead of COUNT to get the star counts.(SUM calculates the value but COUNT calculates the number. With SUM, you can set star value to whatever you want without change your sql. You can have star=2 which shows the actor is important to the movie or have star=-1, which means the actor stinks.)

You may have a look at the sql below:

SELECT a.id, a.name, SUM( p.star ) AS sum
FROM actors a
LEFT JOIN playing p ON p.id_actor = a.id
LEFT JOIN movies m ON p.id_movie = m.id
GROUP BY a.id
ORDER BY sum DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top