我应该如何修改我的查询

时间:2014-11-03 07:41:18

标签: mysql

我使用以下查询确定了类别中最受欢迎的actor(topActor):

SELECT category_id AS cid,
     (SELECT actor_id FROM 
 film_actor JOIN film_category 
   ON  film_actor.film_id = film_category.film_id
         WHERE category_id = cid 
         GROUP BY actor_id
         ORDER BY COUNT(*) DESC
         LIMIT 0,1) AS topActor
 FROM film_actor JOIN film_category 
   ON  film_actor.film_id = film_category.film_id
 GROUP BY category_id


+-----+----------+
| cid | topActor |
+-----+----------+
|   1 |       50 |
|   2 |      150 |
|   3 |       17 |
|   4 |       86 |
|   5 |      196 |
|   6 |       48 |
|   7 |        7 |
|   8 |       79 |
|   9 |      164 |
|  10 |       68 |
|  11 |       27 |
|  12 |      108 |
|  13 |      105 |
|  14 |      107 |
|  15 |       83 |
|  16 |       44 |
+-----+----------+
16 rows in set (0.00 sec)

现在我需要从表格中获取相应的演员 first_name last_name strong> actor ,包含actor_id, first_name last_name 。我知道如何使用PL / SQL或SAS,但我是MySQL的新手。请帮忙!谢谢。

1 个答案:

答案 0 :(得分:0)

据我所知,你想从actor的表中获取fname和lname的值,而外键是actor_id所以我认为这样做。

SELECT category_id AS cid,
 (SELECT actor_id FROM 
 film_actor JOIN film_category 
 ON  film_actor.film_id = film_category.film_id
     WHERE category_id = cid 
     GROUP BY actor_id
     ORDER BY COUNT(*) DESC
     LIMIT 0,1) AS topActor, actor.fname, actor.lname
 FROM film_actor inner JOIN film_category 
 ON  film_actor.film_id = film_category.film_id inner join actor on film_actor.actor_id = actor.id
 GROUP BY category_id

我真的不明白你的问题是什么,所以如果这个答案错了​​,请告诉我哪一部分。