只有在没有多值的情况下才会使用SUM行

时间:2015-01-17 09:38:31

标签: mysql sql

电影表:

+----+------+---------+
| id | title  | price |
+----+------+---------+
|  1 | movie1 |    20 |
|  2 | movie2 |    15 |
|  3 | movie3 |    25 |
|  4 | movie4 |    10 |
+----+------+---------+

分类表:

+-----+--------+
| idd | cat    |
+-----+--------+
|  1  | horror |
|  1  | comedy |
|  2  | drama  |
|  2  | sci-fi |
|  3  | action |
|  4  | sci-fi |
+-----+--------+

我想查询所有电影的价格,除了那些将“科幻”作为其中一个类别的电影。

我试过这个:

select count(distinct id) as no_of_movies, sum(price) as price
from (select distinct id,price
      from movies,categories
      where id=idd and not cat='sci-fi') as tt;

但它仅适用于只有一个类别的电影,例如'movie4' 它仍将“movie2”归为“戏剧”。 那么我怎样才能跳过'movie2'以使输出为45而不是60?

1 个答案:

答案 0 :(得分:1)

试试这个:

select count(distinct id) as no_of_movies, sum(price) as price
from (select distinct id,price
      from movies,categories
      where id=idd and id not in (select idd 
                                  from categories 
                                  where cat = 'sci-fi')) as tt;